package com.itic.mall.mobile.base;



import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.itic.appbase.applications.files.utils.FileHelper;
import com.itic.appbase.applications.sys.sysexception.persistence.model.SysException;
import com.itic.appbase.applications.sys.sysexception.service.SysExceptionService;
import com.itic.appbase.applications.sys.syssetting.service.SysSettingService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.type.DefaultSysSettingKeyValue;
import com.itic.appbase.framework.type.PointsChangeReason;
import com.itic.appbase.framework.utils.CalendarHelper;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.HttpRequestUtils;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.PropertyGetter;
import com.itic.appbase.framework.utils.RandomOrderNumHelper;
import com.itic.appbase.framework.utils.RandomStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.appbase.framework.utils.configuration.PropertyHelper;
import com.itic.mall.mobile.goods.vo.GoodsDetailVo;
import com.itic.mall.mobile.users.info.StoreGoodsVo;
import com.itic.mall.system.goods.coupon.persistence.model.GoodsCoupon;
import com.itic.mall.system.goods.coupon.persistence.model.GoodsCouponExample;
import com.itic.mall.system.goods.coupon.service.GoodsCouponService;
import com.itic.mall.system.goods.goodscategory.persistence.model.GoodsCategory;
import com.itic.mall.system.goods.goodscategory.persistence.model.GoodsCategoryExample;
import com.itic.mall.system.goods.goodscategory.service.GoodsCategoryService;
import com.itic.mall.system.goods.goodssku.service.GoodsSkuService;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpu;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample;
import com.itic.mall.system.goods.goodsspu.service.GoodsSpuService;
import com.itic.mall.system.goods.paramgoods.persistence.model.ParamGoods;
import com.itic.mall.system.goods.paramgoods.persistence.model.ParamGoodsExample;
import com.itic.mall.system.goods.paramgoods.service.ParamGoodsService;
import com.itic.mall.system.goods.skucoupon.persistence.model.SkuCoupon;
import com.itic.mall.system.goods.skucoupon.service.SkuCouponService;
import com.itic.mall.system.groupon.banner.persistence.model.GrouponBanner;
import com.itic.mall.system.groupon.banner.persistence.model.GrouponBannerExample;
import com.itic.mall.system.groupon.banner.service.GrouponBannerService;
import com.itic.mall.system.groupon.category.service.GrouponCategoryService;
import com.itic.mall.system.groupon.goods.service.GrouponGoodsService;
import com.itic.mall.system.groupon.share.service.GrouponShareService;
import com.itic.mall.system.market.marketactivity.persistence.model.MarketActivity;
import com.itic.mall.system.market.marketactivity.persistence.model.MarketActivityExample;
import com.itic.mall.system.market.marketactivity.service.MarketActivityService;
import com.itic.mall.system.market.marketadvert.persistence.model.MarketAdvert;
import com.itic.mall.system.market.marketadvert.persistence.model.MarketAdvertExample;
import com.itic.mall.system.market.marketadvert.service.MarketAdvertService;
import com.itic.mall.system.market.marketbanner.persistence.model.MarketBanner;
import com.itic.mall.system.market.marketbanner.persistence.model.MarketBannerExample;
import com.itic.mall.system.market.marketbanner.persistence.model.MarketBannerExample.Criteria;
import com.itic.mall.system.market.marketbanner.service.MarketBannerService;
import com.itic.mall.system.market.marketmodel.persistence.model.MarketModel;
import com.itic.mall.system.market.marketmodel.persistence.model.MarketModelExample;
import com.itic.mall.system.market.marketmodel.service.MarketModelService;
import com.itic.mall.system.orders.detail.persistence.model.OrdersDetail;
import com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample;
import com.itic.mall.system.orders.detail.service.OrdersDetailService;
import com.itic.mall.system.orders.item.persistence.model.OrdersItem;
import com.itic.mall.system.orders.item.persistence.model.OrdersItemExample;
import com.itic.mall.system.orders.item.service.OrdersItemService;
import com.itic.mall.system.pay.userlog.persistence.model.PayUserlog;
import com.itic.mall.system.pay.userlog.persistence.model.PayUserlogExample;
import com.itic.mall.system.pay.userlog.service.PayUserlogService;
import com.itic.mall.system.project.alipay.persistence.model.Alipay;
import com.itic.mall.system.project.alipay.persistence.model.AlipayExample;
import com.itic.mall.system.project.alipay.service.AlipayService;
import com.itic.mall.system.project.alipaycompany.persistence.model.AlipayCompany;
import com.itic.mall.system.project.alipaycompany.persistence.model.AlipayCompanyExample;
import com.itic.mall.system.project.alipaycompany.service.AlipayCompanyService;
import com.itic.mall.system.project.describe.persistence.model.ProjectDescribe;
import com.itic.mall.system.project.describe.persistence.model.ProjectDescribeExample;
import com.itic.mall.system.project.describe.service.ProjectDescribeService;
import com.itic.mall.system.project.jdset.persistence.model.Jdset;
import com.itic.mall.system.project.jdset.persistence.model.JdsetExample;
import com.itic.mall.system.project.jdset.service.JdsetService;
import com.itic.mall.system.project.proexpress.persistence.model.ProjectExpress;
import com.itic.mall.system.project.proexpress.persistence.model.ProjectExpressExample;
import com.itic.mall.system.project.proexpress.service.ProjectExpressService;
import com.itic.mall.system.project.storescroll.persistence.model.ProjectStoreScroll;
import com.itic.mall.system.project.storescroll.persistence.model.ProjectStoreScrollExample;
import com.itic.mall.system.project.storescroll.service.ProjectStoreScrollService;
import com.itic.mall.system.project.wxcompany.persistence.model.WxCompanyPay;
import com.itic.mall.system.project.wxcompany.persistence.model.WxCompanyPayExample;
import com.itic.mall.system.project.wxcompany.service.WxCompanyPayService;
import com.itic.mall.system.project.wxpay.persistence.model.Wxpay;
import com.itic.mall.system.project.wxpay.persistence.model.WxpayExample;
import com.itic.mall.system.project.wxpay.service.WxpayService;
import com.itic.mall.system.share.sharehistory.persistence.model.ShareHistory;
import com.itic.mall.system.share.sharehistory.service.ShareHistoryService;
import com.itic.mall.system.users.address.persistence.model.Usersaddress;
import com.itic.mall.system.users.address.persistence.model.UsersaddressExample;
import com.itic.mall.system.users.address.service.UsersaddressService;
import com.itic.mall.system.users.pointslog.persistence.model.UsersPointslog;
import com.itic.mall.system.users.pointslog.persistence.model.UsersPointslogExample;
import com.itic.mall.system.users.pointslog.service.UsersPointslogService;
import com.itic.mall.system.users.shoppingcartitem.persistence.model.UsersShoppingCartItem;
import com.itic.mall.system.users.shoppingcartitem.persistence.model.UsersShoppingCartItemExample;
import com.itic.mall.system.users.shoppingcartitem.service.UsersShoppingCartItemService;
import com.itic.mall.system.users.store.persistence.model.UsersStore;
import com.itic.mall.system.users.store.persistence.model.UsersStoreExample;
import com.itic.mall.system.users.store.service.UsersStoreService;
import com.itic.mall.system.users.usercoupon.persistence.model.UsersCoupon;
import com.itic.mall.system.users.usercoupon.persistence.model.UsersCouponExample;
import com.itic.mall.system.users.usercoupon.service.UsersCouponService;
import com.itic.mall.system.users.userscode.persistence.model.UsersCode;
import com.itic.mall.system.users.userscode.persistence.model.UsersCodeExample;
import com.itic.mall.system.users.userscode.service.UsersCodeService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample;
import com.itic.mall.system.users.usersmall.service.UsersMallService;
import com.itic.mall.system.users.userstoken.persistence.model.UsersToken;
import com.itic.mall.system.users.userstoken.persistence.model.UsersTokenExample;
import com.itic.mall.system.users.userstoken.service.UsersTokenService;

import net.sf.json.JSONObject;

public class BaseMobileInterface
     extends BaseController {
	protected static String Url = "http://120.55.205.5/webservice/sms.php?method=Submit";//发送短信的URL
	
	@Autowired
	protected WxCompanyPayService wxCompanyPayService;
	@Autowired
	protected UsersaddressService usersaddressService;
	@Autowired 
	protected AlipayCompanyService alipayCompanyService;
	@Autowired
	protected PayUserlogService payUserlogService;
	@Autowired
	protected UsersPointslogService usersPointslogService;
	@Autowired
	protected ProjectStoreScrollService projectStoreScrollService;
	@Autowired 
	protected UsersStoreService usersStoreService;
	@Autowired
	protected ProjectExpressService projectExpressService;
	@Autowired
	protected ProjectDescribeService projectDescribeService;
	@Autowired
    protected SysSettingService sysSettingService;
	@Autowired 
	protected JdsetService jdsetService;
	@Autowired 
	protected WxpayService wxpayService;
	@Autowired 
	protected AlipayService alipayService;
	@Autowired
    protected SysExceptionService sysExceptionService;
	@Autowired
    protected UsersMallService usersMallService;
	@Autowired
	private UsersCodeService usersCodeService;
	@Autowired
    protected UsersTokenService usersTokenService;
	@Autowired
	protected MarketBannerService marketBannerService;
	@Autowired
	protected GrouponBannerService grouponBannerService;
	@Autowired 
	protected GoodsSpuService goodsSpuService;
	@Autowired 
	protected GrouponCategoryService grouponCategoryService;
	@Autowired 
	protected GrouponGoodsService grouponGoodsService;
	@Autowired 
	protected GrouponShareService grouponShareService;
	@Autowired
	protected UsersCouponService usersCouponService;
	@Autowired
	protected OrdersDetailService ordersDetailService;
	@Autowired
	protected OrdersItemService ordersItemService;
	@Autowired
	protected ParamGoodsService paramGoodsService;
	@Autowired
	protected GoodsCouponService goodsCouponService;
	@Autowired
	protected MarketAdvertService marketAdvertService;
	@Autowired
	protected MarketModelService marketModelsService;
	@Autowired
	protected GoodsCategoryService goodsCategoryService;
	@Autowired
	protected MarketActivityService marketActivityService;
	@Autowired
	private UsersShoppingCartItemService usersShoppingCartItemService;
	@Autowired
	private GoodsSkuService goodsSkuService;
	@Autowired
	private ShareHistoryService shareHistoryService;
	@Autowired
	private SkuCouponService skuCouponService;
	
	protected static final String RequestUser = "RequestUser";
	
	protected static final String ORG_CODE = "unknown";
	protected static final String CREATE_USER = "unknown";
	//平台类型
	protected static final String PLATFORM_YHJ = "1";
	protected static final String PLATFORM_JD = "2";
	protected static final String PLATFORM_TM = "3";
	protected static final String PLATFORM_ESYP = "4";
	protected static final String PLATFORM_TB = "5";
	
	//接口返回键
    protected static final String RESULT = "result";
    protected static final String DATA = "data";
    protected static final String CODE = "code";
    protected static final String MSG = "msg";
    protected static final String IS_STORE = "isStore";
    
    protected static final String SUCCESS = "success";
    protected static final String FAIL = "fail";
    protected static final String LOGIN = "login";
    
    protected static final String SUCCESS_ERROR_CODE = "10000";//请求成功
    protected static final String LOGIN_ERROR_CODE = "10001";//用户未登入或者TOKEN无效
    protected static final String PARAM_ERROR_CODE = "10002";//缺少必填参数
    protected static final String SERVER_ERROR_CODE = "10003";//服务器异常
    
    protected static final String PHONE_CODE_ERROR_CODE = "10004";//验证码无效
    protected static final String PWD_ERROR_CODE = "10005";//用户名或密码无效
    
    
    
    protected static final String TOKEN_ERROR_CODE = "10006";//token无效
    protected static final String OPENID_ERROR_CODE = "10007";//OPENID无效
    protected static final String UNIONID_ERROR_CODE = "10008";//UNIONID 无效 
    protected static final String INVITING_ERROR_CODE ="10009";//用户邀请码无效
    protected static final String STORE_CODE_ERROR_CODE = "10010";//店铺的代码无效
    protected static final String PRODUCT_ID_ERROR_CODE = "10011";//商品ID无效
    protected static final String NOTICE_ID_ERROR_CODE = "10012";//商品ID无效
    protected static final String LESS_MONEY_ERROR_CODE = "10013";//
    protected static final String NONE_EXPRESS_ERROR_CODE = "10014";//
    protected static final String ORDER_NULL_ERROR_CODE = "10015";//
    protected static final String PRODUCT_STORED_ERROR_CODE = "10016";//
    protected static final String PHONE_NULL_ERROR_CODE = "10017";//
    protected static final String PHONE_REGED_ERROR_CODE = "10018";//手机号码已注册过了
    protected static final String FAIL_CODE_ERROR_CODE = "10019";//验证码发送失败
    protected static final String OFF_SITE_ERROR_CODE = "10020";//验证码发送失败
    protected static final String UNIONID_NULL_ERROR_CODE = "10021";//验证码发送失败
    protected static final String OPENID_NULL_ERROR_CODE = "10022";//验证码发送失败
    protected static final String LUNBO_NULL_ERROR_CODE = "10023";//轮播图获取失败
    protected static final String MODEL_NULL_ERROR_CODE = "10024";//模块信息获取失败
    protected static final String ADVERT_ONE_NULL_ERROR_CODE = "10025";//广告图一获取失败
    protected static final String SECHAND_NULL_ERROR_CODE = "10026";//二手好货获取失败
    protected static final String FIND_GOOD_NULL_ERROR_CODE = "10027";//爆品专去获取失败
    protected static final String ADVERT_TWO_NULL_ERROR_CODE = "10028";//广告图二获取失败
    protected static final String RANK_NULL_ERROR_CODE = "10029";//排行榜获取失败
    protected static final String HOT_NULL_ERROR_CODE = "10030";//热门活动专区获取失败
    protected static final String ORDER_ERROR_CODE = "10031";//订单信息为空
    protected static final String REDPAC_ERROR_CODE = "10032";//红包信息获取失败
    protected static final String EXPRESS_ERROR_CODE = "10033";//物流信息获取失败
    protected static final String AFTERSALE_ERROR_CODE = "10034";//售后信息获取失败
    protected static final String USER_MODEL_ERROR_CODE = "10035";//模块信息获取失败
    protected static final String USER_MODEL_SCROLL_REL_ERROR_CODE="10036";//模块条幅信息获取失败
    protected static final String INDEXPAGE_ERROR_CODE = "10037";//欢迎页获取失败
    protected static final String COMPLAINT_FEEDBACK_ERROR_CODE = "10038";//反馈信息获取失败
    protected static final String PROJECT_LOGIN_PAGE_ERROR_CODE = "10039";//注册登录页获取图片失败
    protected static final String COUPON_USE_ERROR_CODE = "10040";//该订单不能使用此红包券
    protected static final String USERS_ADDRESS_ERROR_CODE = "10041";//用户地址信息获取失败
    protected static final String PWD_CONFIRM_ERROR_CODE = "10042";//新密码与确认密码不一致
    protected static final String RECEIVER_ERROR_CODE = "10043";//收货人信息为空
    protected static final String ORDER_GOODS_ERROR_CODE = "10044";//商品信息为空
    protected static final String ORDER_COUPON_ERROR_CODE = "10045";//优惠券信息为空
    protected static final String ORDER_POINTS_ERROR_CODE = "10046";//积分信息为空
    protected static final String ORDER_EXPRESS_ERROR_CODE = "10047";//物流信息为空
    protected static final String ORDER_PAY_ERROR_CODE = "10048";//支付信息为空
    protected static final String SHOPPING_CART_ITEM_ERROR_CODE = "10049";//购物车项获取失败
    protected static final String AFTERSALE_TYPE_EXPRESS_ERROR_CODE = "10050";//售后类型不需要填写物流
    protected static final String PRODUCT_NOT_FIND_ERROR_CODE = "10051";//商品未找到错误代码;
    protected static final String PRODUCT_SALES_NULL_ERROR_CODE = "10052";//此款商品已售空;
    protected static final String PRODUCT_DATA_ERROR_CODE = "10053";//商品数据异常;
    protected static final String PRODUCT_PROPERTY_LESS_ERROR_CODE = "10054";//商品属性不全！
    protected static final String Not_OPEND_YDZ_ERROR_CODE = "10055";//未开通云店主！
    protected static final String Amount_NOT_WITHDRAWLS_CODE = "10056";//余额不足提现！
    protected static final String Amount_NOT_FEE_CODE = "10057";//余额不足手续费！
    protected static final String ORDER_HAD_SENDING_CODE = "10058";//订单中含有未发货商品
    protected static final String NOT_SELECT_SKU_COUNT_CODE = "10059";//未选择商品数量
    protected static final String SHOPPING_CART_ERROR_CODE = "10060";//购物车获取失败
    protected static final String GOODS_NOT_EXIST_CODE = "10061";//
    protected static final String ORDER_SEND_STATE_ERROR = "10062";//订单已发货或不存在
    protected static final String ORDER_ITEM_ERROR_CODE = "10063";//订单项获取失败
    protected static final String ORDER_ADD_REMIND_SEND_ERROR = "10064";//此商品已添加提醒发货
    protected static final String GOODS_NOT_FIND_ERROR_CODE = "10065";//商品未找到
    protected static final String CONPRICE_NULL_ERROR_CODE = "10066";//优惠券已领空
    protected static final String LINK_NULL_ERROR_CODE = "10067";//该链接已删除
    protected static final String MAX_NINE_ERROR_CODE = "10068";//该链接已删除
    protected static final String SKU_NUMBER_NOT_ENOUGH_CODE = "10069";//商品库存不足
    protected static final String OBJECT_NULL_ERROR_MSG = "10070";  //对象获取失败
    protected static final String AlREADY_RECEIVE_COUPON_ERROR_CODE = "10071";
    protected static final String INVITE_CODE_ERROR_CODE = "10072";
    protected static final String UNIONID_BINED_ERROR_CODE = "10073";
    
    protected static final String COUPON_EXPIRETIME_ERROR_CODE = "10072";
    protected static final String AFTERSALE_ALREADY_PENDING_ERROR_CODE = "10073";
    protected static final String NOT_AGREE_RETURN_ERROR_CODE = "10074";
    protected static final String PRODUCT_SKU_DATA_ERROR_CODE = "10075";
    protected static final String ORDER_AFTERSALE_ALREADY_CODE = "10076";
    protected static final String YUNED_ERROR_CODE = "10077";
    protected static final String PARENT_ID_ERROR_CODE = "10078";
    protected static final String RUZHUED_ERROR_CODE = "10079";
    protected static final String TIJIANED_ERROR_CODE = "10080";
    protected static final String OPENID_PAY_NULL_ERROR_CODE = "10081";
    protected static final String USER_NULL_ERROR_CODE = "10082";
    protected static final String USER_BINDED_ERROR_CODE = "10083";
    protected static final String NOT_YUNED_ERROR_CODE = "10084";
    protected static final String YUNID_NULL_ERROR_CODE = "10085";
    protected static final String MARKET_ID_ERROR_CODE = "10086";
    protected static final String USER_ALREADY_HELP_ERROR_CODE = "10087";

    protected static final String BANLANCE_NOT_ENOUGH_CODE = "10088";
    

    protected static final String PAY_FAILD_CODE = "10089";
    
    protected static final String ORDER_ADD_REMIND_SEND_MSG = "此商品已添加提醒发货";//此商品已添加提醒发货
    protected static final String ORDER_ITEM_ERROR_MSG = "订单项获取失败";//订单项获取失败
    protected static final String ORDER_SEND_STATE_MSG = "订单已发货或不存在";//订单已发货或不存在

    protected static final String SHOPPING_CART_ERROR_MSG = "购物车获取失败";//购物车获取失败

    protected static final String AFTERSALE_TYPE_EXPRESS_ERROR_MSG = "售后类型不需要填写物流";
    protected static final String SHOPPING_CART_ITEM_ERROR_MSG = "购物车项获取失败";
    protected static final String ORDER_PAY_ERROR_MSG = "支付信息为空";
    protected static final String ORDER_EXPRESS_ERROR_MSG = "物流信息为空";
    protected static final String ORDER_POINTS_ERROR_MSG = "积分信息为空";
    protected static final String ORDER_COUPON_ERROR_MSG = "优惠券信息为空";
    protected static final String ORDER_GOODS_ERROR_MSG = "商品信息为空";
    protected static final String RECEIVER_ERROR_MSG = "收货人信息为空";
    protected static final String YUNID_NULL_ERROR_MSG = "云店主无效";
    
    protected static final String PWD_CONFIRM_ERROR_MSG = "新密码与确认密码不一致";
    protected static final String USERS_ADDRESS_ERROR_MSG = "用户地址信息获取失败";
    protected static final String COUPON_USE_ERROR_MSG = "该订单不能使用此红包券"; 
    protected static final String PROJECT_LOGIN_PAGE_ERROR_MSG = "注册登录页获取图片失败";
    protected static final String COMPLAINT_FEEDBACK_ERROR_MSG = "反馈信息获取失败！";
    protected static final String INDEXPAGE_ERROR_MSG = "欢迎页获取失败！";
    protected static final String USER_MODEL_SCROLL_REL_ERROR_MSG="模块条幅信息获取失败";
    protected static final String USER_MODEL_ERROR_MSG = "模块信息获取失败";
    protected static final String AFTERSALE_ERROR_MSG = "售后信息获取失败";
    protected static final String EXPRESS_ERROR_MSG = "物流信息获取失败";
    protected static final String OBJECT_ERROR_MSG = "对象获取失败";
    protected static final String REDPAC_ERROR_MSG = "红包信息获取失败";
    protected static final String ORDER_ERROR_MSG = "订单信息为空或不存在！";
    protected static final String LUNBO_ERROR_MSG = "轮播图获取失败！";
    protected static final String MODEL_ERROR_MSG = "模块信息获取失败！";
    protected static final String ADVERT_ONE_ERROR_MSG = "广告图一获取失败！";
    protected static final String SECHAND_ERROR_MSG = "二手好货获取失败！";
    protected static final String FIND_GOOD_ERROR_MSG = "爆品专去获取失败！";
    protected static final String ADVERT_TWO_ERROR_MSG = "广告图二获取失败！";
    protected static final String RANK_ERROR_MSG = "排行榜获取失败！";
    protected static final String HOT_ERROR_MSG = "热门活动专区获取失败！";
    protected static final String SUCCESS_ERROR_MSG = "请求成功！";//服务器异常
    protected static final String SERVER_ERROR_MSG = "服务器繁忙，请重试！";//服务器异常
    protected static final String PARAM_ERROR_MSG = "缺少必填参数，请检查！";//参数不正确
    protected static final String LOGIN_ERROR_MSG = "登入过期，请重新登入！";//用户未登入
    protected static final String PHONE_CODE_ERROR_MSG = "验证码无效！";//验证码无效
    protected static final String PWD_ERROR_MSG = "用户名或密码不正确";//验证码无效
    protected static final String TOKEN_ERROR_MSG = "登入授权码失效!";//验证码无效
    protected static final String OPENID_ERROR_MSG = "微信公众号授权码无效!";//验证码无效
    protected static final String UNIONID_ERROR_MSG = "微信授权码无效!";//验证码无效
    protected static final String INVITING_ERROR_MSG = "邀请码无效！";//注册成为商家的邀请码无效
    protected static final String STORE_CODE_ERROR_MSG = "店铺的代码无效！";//店铺的代码无效
    protected static final String PRODUCT_ID_ERROR_MSG ="商品唯一标识无效！";//商品ID无效
    protected static final String NOTICE_ID_ERROR_MSG ="公告唯一标识无效！";//商品ID无效
    protected static final String LESS_MONEY_ERROR_MSG ="很抱歉，用户金额不足！";//商品ID无效
    protected static final String NONE_EXPRESS_ERROR_MSG = "暂未查询物流信息！";//物流为空
    protected static final String ORDER_NULL_ERROR_MSG = "订单无效！";//物流为空
    protected static final String PRODUCT_STORED_ERROR_MSG = "商品已收藏过了！";//物流为空
    protected static final String PHONE_NULL_ERROR_MSG = "手机号码未注册！";//
    protected static final String PHONE_REGED_ERROR_MSG = "手机号码已注册过了，请更换手机号码！";//
    protected static final String FAIL_CODE_ERROR_MSG = "今日验证码次数用完了！";//
    protected static final String OFF_SITE_ERROR_MSG = "您的账号已异地登入！";//
    protected static final String UNIONID_NULL_ERROR_MSG = "微信未绑定手机号码,请先注册！";//验证码发送失败
    protected static final String OPENID_NULL_ERROR_MSG = "微信公众号未绑定手机号码！";//验证码发送失败
    protected static final String AFTER_SALE_APPLY_TYPE = "type";
    protected static final String AFTER_SALE_APPLY_TIME = "applytime";
    protected static final String AFTER_SALE_APPLY_REFUND_CODE = "1";//问题类型(1：仅退款，2:退款退货，3：换货，4：维修)
    protected static final String AFTER_SALE_APPLY_CANCEL_CODE = "2";//问题类型(1：仅退款，2:退款退货，3：换货，4：维修)
    protected static final String AFTER_SALE_APPLY_CHANGE_CODE = "3";//问题类型(1：仅退款，2:退款退货，3：换货，4：维修)
    protected static final String AFTER_SALE_APPLY_FIX_CODE = "4";//问题类型(1：仅退款，2:退款退货，3：换货，4：维修)
    protected static final String AFTER_SALE_APPLY_REFUND_MSG = "仅退款";//问题类型(1：仅退款，2:退款退货，3：换货，4：维修)
    protected static final String AFTER_SALE_APPLY_CANCEL_MSG = "退款退货";//问题类型(1：仅退款，2:退款退货，3：换货，4：维修)
    protected static final String AFTER_SALE_APPLY_CHANGE_MSG = "换货";//问题类型(1：仅退款，2:退款退货，3：换货，4：维修)
    protected static final String AFTER_SALE_APPLY_FIX_MSG = "维修";//问题类型(1：仅退款，2:退款退货，3：换货，4：维修)
    protected static final String AFTER_SALE_SUCCESS_APPLY_RESULT = "售后服务单申请成功";
    protected static final String AFTER_SALE_FAIL_APPLY_RESULT = "售后服务单申请失败";
    protected static final String PRODUCT_NOT_FIND_ERROR_MSG = "商品未找到！";
    protected static final String PRODUCT_SALES_NULL_ERROR_MSG = "此款商品已售空!";
    protected static final String PRODUCT_DATA_ERROR_MSG = "商品数据异常!";
    protected static final String PRODUCT_PROPERTY_LESS_ERROR_MSG = "商品属性不全！";
    protected static final String Not_OPEND_YDZ_ERROR_MSG = "未开通云店主!";
    protected static final String Amount_NOT_WITHDRAWLS_MSG = "余额不足提现！";//余额不足提现！
    protected static final String Amount_NOT_FEE_MSG = "余额不足扣手续费";//余额不足手续费！

    protected static final String ORDER_HAD_SENDING_MSG = "订单中含有未发货商品";//订单中含有未发货商品！
    

    protected static final String TOTALINVENTORYS_ERROR_MSG = "库存信息错误";//
    protected static final String SKUTOTALINVENTORYS_NULL_ERROR_MSG = "库存信息为空";
    protected static final String NOT_SELECT_SKU_COUNT_MSG = "未选择商品数量";//
    protected static final String GOODS_NOT_EXIST_MSG = "订单中商品已下架";//
    protected static final String GOODS_NOT_FIND_ERROR_MSG = "商品未找到";//商品未找到
    protected static final String CONPRICE_NULL_ERROR_MSG = "优惠券已抢完了";//优惠券已领空
    protected static final String LINK_NULL_ERROR_MSG = "该商品已下架了";
    protected static final String MAX_NINE_ERROR_MSG = "最多只能分享九个商品";//该链接已删除
    protected static final String SKU_NUMBER_NOT_ENOUGH_MSG = "商品库存不足";//商品库存不足
   
    protected static final String AlREADY_RECEIVE_COUPON_ERROR_MSG = "该优惠券已领取";
    protected static final String COUPON_EXPIRETIME_ERROR_MSG = "该优惠券已过期";
    protected static final String AFTERSALE_ALREADY_PENDING_ERROR_MSG = "售后处理中,不能撤销";
    protected static final String NOT_AGREE_RETURN_ERROR_MSG = "未同意换货";
    protected static final String PRODUCT_SKU_DATA_ERROR_MSG = "款式已卖完！";
    protected static final String INVITE_CODE_ERROR_MSG = "邀请码无效";
    protected static final String ORDER_AFTERSALE_ALREADY_MSG = "售后已存在";
    protected static final String YUNED_ERROR_MSG = "您已成为云店主了";
    protected static final String PARENT_ID_ERROR_MSG = "邀请人无效，请确认邀请人信息！";
    protected static final String RUZHUED_ERROR_MSG = "已提交申请开店了！";
    protected static final String TIJIANED_ERROR_MSG = "您已提交申请了";
    
    protected static final String OPENID_PAY_NULL_ERROR_MSG = "微信公众号未授权";
    protected static final String USER_NULL_ERROR_MSG = "找不到用户信息";
    protected static final String USER_BINDED_ERROR_MSG = "该用户已绑定了微信，请更换用户信息";
    protected static final String NOT_YUNED_ERROR_MSG = "您还未成为店主";
    protected static final String UNIONID_BINED_ERROR_MSG = "微信已绑定其它用户，请更换微信";
    protected static final String MARKET_ID_ERROR_MSG = "活动已取消，请重新选择分享";

    protected static final String USER_ALREADY_HELP_ERROR_MSG = "该微信好友已经助力过了";
    

    protected static final String BANLANCE_NOT_ENOUGH_MSG = "余额不足";

    protected static final String PAY_FAILD_MSG = "余额支付失败";
 	//商品过滤字段
    protected static String[] commonIgnoreProperties = new String[] { "createUser", "isEffective", "updateTime", "note",
  			"createTime", "orgCode" };
  	
    // 返回通用属性黑名单
    protected static String[] spuIgnoreProperties = new String[] { "totalFeedback", "isServenBack", "detailImageUrls", "reorder", "goodsSource",
														  			"orderHot", "goodsSubtitle", "marketProfitPercent", "orderJingping", "marketDate",
														  			"totalGoodFeedback", "banners", "isShow", "companyId", "note", "reorder", "categoryId",
														  			"createUser", "isEffective", "updateTime", "orgCode", "isVisible", "createTime",
														  			"goodsTitle", "brandId", "spuNum", "isFreePost", "isJingping", "couponTab", "specialId",
														  			"skuName", "pcCommission", "isSpecial", "pcPrice", "couponNote",
														  			"pcCommissionShare", "prmTab", "manJianNote",
														  			"discountRate", "manJianNote", "isShare", "skuUrl","marketProfit","bannerTip",
														  			"realRate","discountPrice","orginPrice","wlCommissionShare","wlPrice","isOnTime",
														  			"startTime","endTime","openTime","isQualityAssurance","conUrl","isYwym","orderYwym","totalClick","totalShare"};
														    
    // 返回SKU属性黑名单
    protected static String[] skuIgnoreProperties = new String[] { "createUser", "isEffective", "updateTime", "orgCode","note","createTime","reorder","skuOrginPrice","skuNum","skuBanners","maxBuyNum","minBuyNum" };
    /**
     * 验证码是否有效
     * @param phone
     * @param code
     * @return
     */
    public boolean isEffectiveCode( String phone, String code ){
    	boolean result = false;
    	UsersCodeExample example = new UsersCodeExample();
    	com.itic.mall.system.users.userscode.persistence.model.UsersCodeExample.Criteria criteria =example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andCodeEqualTo(code);
    	criteria.andPhoneEqualTo(phone);
    	criteria.andExpiredTimeGreaterThanOrEqualTo(new Date());
    	
    	List<UsersCode> list = usersCodeService.list(example);
    	if( list.size() > 0 ){
    		result = true;
    	}
    	return result;
    }
    
    /**
     * 异常日志
     * @param e
     */
    public void logException( String className, String methodName, String message, String desc, Exception e ){
    	try{  
    	   Date now = new Date();
		   String nowString = DateHelper.formatDateTime(now);
		   
		   SysException exception = new SysException();
		   exception.setId(IdGen.uuid());
		   exception.setExceptionClass(className);
		   exception.setExceptionMethod(methodName);
		   
		   //exception.setExceptionNote();
		   exception.setExceptionNote(desc);
		   
		   exception.setExceptionTime(nowString);
		   
		   exception.setExceptionMessage(message);
		   
		   StringBuffer bf = new StringBuffer();
		   bf.append(FileHelper.getRootDir());
		   bf.append("exception");
		   bf.append(File.separator);
		   bf.append(DateHelper.getDateStringByDate(new Date(), "yyyy-MM-dd"));
		   bf.append(File.separator);
		   String filePath = bf.toString();
		   File f=new File(filePath);
		   if(!f.exists()){
		    	 f.mkdirs();
		   }
		   bf.append(IdGen.uuid());
           bf.append(".txt");
           filePath = bf.toString();
		   File tempfile =new File(filePath);
		   if(!tempfile.exists()){
		    	tempfile.createNewFile();
		   }
         
		   //输出一个错误日志文件
		   FileOutputStream out = new FileOutputStream(filePath);//确认流的输出文件和编码格式，此过程创建了“test.txt”实例
			
		   PrintStream printStream = new PrintStream(out);
		   e.printStackTrace(printStream);
		   out.close();
		   String replace = filePath.replace(FileHelper.getRootDir(), "");
		   //保存全路径
		   exception.setExceptionFilepath(PropertyGetter.getString("app.download.path") +"mall_fileupload/"+ replace);
		   sysExceptionService.add(exception);
		   
    	}catch(Exception temp){
		   temp.printStackTrace();
	    }
    }

    
    /**
     * 判断是否还有更多
     * @param request
     * @param count
     * @return
     */
    protected String isMore( HttpServletRequest request,int count){
    	String result = "have";
    	
    	String recordNow = this.getCleanParams(request, IticConst.RECORD_NOW);
        String pageSize = this.getCleanParams(request, IticConst.PAGE_SIZE);
        
        if( StringHelper.isEmpty(recordNow) ){
        	recordNow = "0";
        }
        
        if( StringHelper.isEmpty(pageSize) ){
        	pageSize = "10";
        }
        
        String addString = NumberStringHelper.addString(recordNow, "1");
        String mulString = NumberStringHelper.mulString(addString, pageSize);
        
        if( !NumberStringHelper.isGreaterNoEqual(count+"", mulString) ){
        	result = "none";
        }
        return result;
    }
    /**
     * 是否跨域方法
     * @param response
     * @return
     */
    public HttpServletResponse isCrrossDomain( HttpServletResponse response ){
    	//是否允许跨域
    	String isCrrossDomain = sysSettingService.getByKey("IS_CRROSS_DOMAIN");
    	String isSetCrrossDomain = PropertyGetter.getString("app.is.crross.domain");
    	if( isSetCrrossDomain.equals( isCrrossDomain ) ){
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true");
    	}
    	return response;
    }
    
    
    /**
     * 获取随机TOKEN方法
     */
    public String getToken(){
    	String orderNumber = RandomOrderNumHelper.getOrderNumber();
    	String uuid = IdGen.uuid();
    	return orderNumber + uuid;
    }
    
    /**
     * 获取 Token的过期 时间
     * @param date
     * @return
     */
    public Date getExpiredTimeToken(Date date){
    	String dayStr = "7";//默认TOKEN有效期为7天
    	String daySet =sysSettingService.getByKey("TOKEN_EXPIRED_DAY");
    	if( StringHelper.isNotBlank(daySet) ){
    		dayStr = daySet;
    	}
    	Date dateAfter = CalendarHelper.getDateAfter(date, Integer.parseInt(dayStr));
    	return dateAfter;
    }
    /**
     * 获取是否开启少于多少钱不让提现
     * */
    public boolean getIsOpenLessMoneyNotWithDraw() {
    	boolean flag = false;
    	String isOpen = this.sysSettingService.getByKey("IsOpenLessMoneyNotWithDraw");
    	if(StringUtils.isNotEmpty(isOpen)) {
    		flag = Boolean.parseBoolean(isOpen);
    	}
    	return flag;
    	
    }
    
    /**
     * 获取少于的钱数 不让提现
     * 
     * */
    public double getlessMoneyNotWithDraw() {
    	double amount=100;
    	String money = this.sysSettingService.getByKey("lessMoneyNotWithDraw");
    	if(StringUtils.isNotEmpty(money))
    		amount = Double.parseDouble(money);
    	return amount;
    }
    /**
     * 获取 验证码的过期 时间
     * @param date
     * @return
     */
    public Date getExpiredTimeCode(Date date){
    	String minuteStr = "5";//默认CODE有效期为5分
    	String minuteSet =sysSettingService.getByKey("CODE_EXPIRED_MINUTE");
    	if( StringHelper.isNotBlank(minuteSet) ){
    		minuteStr = minuteSet;
    	}
    	Date dateAfter = CalendarHelper.getMinuteAfter(date, Integer.parseInt(minuteStr));
    	return dateAfter;
    }
    
    /**
     * 获取当前版本信息
     * @return
     */
    public String getVersionMsg(){
    	String versionStr = "1.0.0";//默认CODE有效期为5分
    	String versionSet =sysSettingService.getByKey("VERSION_CURRENT");
    	if( StringHelper.isNotBlank(versionSet) ){
    		versionStr = versionSet;
    	}
    	return versionStr;
    }
    
    
    /**
     * 用户默认的头像地址
     * @return
     */
    public String getDefaultHeadImg(){
    	String defaultValue = DefaultSysSettingKeyValue.defaultHeadImg.getValue();
		String sysValue = sysSettingService.getByKey(DefaultSysSettingKeyValue.defaultHeadImg.getKey());
		if( StringHelper.isNotBlank(sysValue) ){
			defaultValue = sysValue;
		}
		return defaultValue;
    }
    
    
    public double getFeeAmount() {
    	double fee = 0.5;
    	String feeAmount = sysSettingService.getByKey("WithDrawFee");
    	if (StringUtils.isNotEmpty(feeAmount)){
    		fee = Double.parseDouble(feeAmount);
    	}
    	return fee;
    	
    }
    /**
     * 发送验证码通用方法（注册与修改密码需要用到）
     * @param telphone  手机号码
     * @return
     */
    public String sendMassage(String telphone,String codeCont){
    	    String result = FAIL;
    	  
 	    
    	    HttpClient client = new HttpClient(); 
 			PostMethod method = new PostMethod(Url); 
 				
 			//client.getParams().setContentCharset("GBK");		
 			client.getParams().setContentCharset("UTF-8");
 			method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

 			//String content = new String("您的验证码是："+codeCont+"。请不要把验证码泄露给其他人。"); 
  		    String content = new String("您的验证码是：【"+codeCont+"】，3分钟有效时间，请不要把验证码泄露给其他人。");
 			// 您的验证码是：【变量】，3分钟有效时间，请不要把验证码泄露给其他人。
  		    NameValuePair[] data = {//提交短信
  				    //new NameValuePair("account", "cf_jdhj"), 
  				    //new NameValuePair("password", "a123456"), //密码可以使用明文密码或使用32位MD5加密
  				    new NameValuePair("account", "C11714710"), 
 				    new NameValuePair("password", "85202a35086eb358e717dbf9ebc6e9bc"), //密码可以使用明文密码或使用32位MD5加密
  				    //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
  				    new NameValuePair("mobile", telphone), 
  				    new NameValuePair("content", content),
  			};
 			
 			method.setRequestBody(data);		
 			
 			
 			try {
 				client.executeMethod(method);	
 				 
 				String SubmitResult =method.getResponseBodyAsString();
 						
 				//System.out.println(SubmitResult);

 				Document doc = DocumentHelper.parseText(SubmitResult); 
 				Element root = doc.getRootElement();


 				String code = root.elementText("code");	
 				//String msg = root.elementText("msg");	
 				//String smsid = root.elementText("smsid");	
 				
 				
 				//System.out.println(code);
 				//System.out.println(msg);
 				//System.out.println(smsid);
 							
 				if("2".equals(code)){
 					result = SUCCESS;
 				}else{
 					result = FAIL;
 				}
 				
 			} catch (Exception e) {
 				e.printStackTrace();
 			}
    	
 		return result;
    }
    
    
    
    public String getDefaultVideoImage(){
    	String defaultImage = "http://www.huifakeji.com/default/default.png";
    	String tmp = sysSettingService.getByKey("DEFAULT_HEAD_IMAGE");
    	if( StringHelper.isNotBlank(tmp) ){
    		defaultImage=tmp;
    	}
    	return  defaultImage;
    }
    
    //token是否有效且没有异地登入
    public String isEffectiveToken( String token, String appId ){
    	String result = FAIL;
    	//验证TOKEN是否有效
		UsersTokenExample example = new UsersTokenExample();
		com.itic.mall.system.users.userstoken.persistence.model.UsersTokenExample.Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);//是否有效
		criteria.andAccessTokenEqualTo(token);//token是否一样
		criteria.andAppIdEqualTo(appId);//appId是否一致
		criteria.andIsOffsiteEqualTo(DBConst.FALSE);//是否异地登入
		criteria.andExpiredTimeGreaterThanOrEqualTo(new Date());//是否过期
		List<UsersToken> list = usersTokenService.list(example);
		if( list.size()>0 ){
			result = SUCCESS;
		}
		return result;
    } 
    
    //token是否有效
    public UsersToken getTokenByTokenAndAppId( String token, String appId ){
    	UsersToken result = null;
    	//验证TOKEN是否有效
		UsersTokenExample example = new UsersTokenExample();
		com.itic.mall.system.users.userstoken.persistence.model.UsersTokenExample.Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);//是否有效
		criteria.andAccessTokenEqualTo(token);//token是否一样
		criteria.andAppIdEqualTo(appId);//appId是否一致
		//criteria.andIsOffsiteEqualTo(DBConst.FALSE);//是否异地登入
		criteria.andExpiredTimeGreaterThanOrEqualTo(new Date());//是否过期
		List<UsersToken> list = usersTokenService.list(example);
		if( list.size()>0 ){
			result = list.get(0);
		}
		return result;
    } 
    /**
	 * 根据用户ID获取用户姓名
	 * @param userId
	 * @return
	 */
	public String getUserName(String userId){
		String userName = null;
		if(StringHelper.isNotBlank(userId)){
			UsersMallExample example = new UsersMallExample();
    		com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andIdEqualTo(userId);
    		List<UsersMall> list = usersMallService.list(example);
    		if(list.size()>0){
    			userName = list.get(0).getUserNickName();
    		}
		}
		return userName;
	}
	/**
	 * 根据用户ID 寻找该用户的所有下级
	 * @param userId
	 * @return
	 */
    public List<UsersMall> getusersTeam(String userId){
    	List<UsersMall> teamList = new ArrayList<UsersMall>();
    	if(StringHelper.isNotBlank(userId)){
    		//在用户表中寻找parent_id是该用户Id的用户
    		UsersMallExample example = new UsersMallExample();
    		com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andParentIdEqualTo(userId);
    		List<UsersMall> list = usersMallService.list(example);
    		if(list.size()>0){
    			for(UsersMall users:list){
        			teamList.add(users);
        		} 
    		}
    	}
		return teamList;
    }
    /**
     * 根据时间段查询用户下级用户
     * @param userId
     * @param startTime
     * @param endTime
     * @return
     */
    public List<UsersMall> getusersTeamByTime(String userId,Date startTime,Date endTime){
    	List<UsersMall> teamList = new ArrayList<UsersMall>();
    	if(StringHelper.isNotBlank(userId)){
    		//在用户表中寻找parent_id是该用户Id的用户
    		UsersMallExample example = new UsersMallExample();
    		com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andParentIdEqualTo(userId);
    		criteria.andCreateTimeBetween(startTime, endTime);
    		List<UsersMall> list = usersMallService.list(example);
    		if(list.size()>0){
    			for(UsersMall users:list){
        			teamList.add(users);
        		} 
    		}
    	}
		return teamList;
    }
    /**
     * 根据电话或者用户姓名查询用户下级
     * @param userId
     * @param userName
     * @param userPhone
     * @return
     */
    public List<UsersMall> getusersTeamByMsg(String userId,String userName,String userPhone){
    	List<UsersMall> teamList = new ArrayList<UsersMall>();
    	if(StringHelper.isNotBlank(userId)){
    		//在用户表中寻找parent_id是该用户Id的用户
    		UsersMallExample example = new UsersMallExample();
    		com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andParentIdEqualTo(userId);
    		if(StringHelper.isNotBlank(userPhone) && StringHelper.isNotBlank(userName)){
        		criteria.andUserPhoneEqualTo(userPhone);
        		criteria.andUserNickNameEqualTo(userName);
    		}
    		if(StringHelper.isNotBlank(userPhone) && StringHelper.isBlank(userName)){
        		criteria.andUserPhoneEqualTo(userPhone);
    		}
    		if(StringHelper.isBlank(userPhone) && StringHelper.isNotBlank(userName)){
        		criteria.andUserNickNameEqualTo(userName);
    		}
    		List<UsersMall> list = usersMallService.list(example);
    		if(list.size()>0){
    			for(UsersMall users:list){
        			teamList.add(users);
        		} 
    		}
    	}
		return teamList;
    }
    
    public int getTeamNum(String userId){
    	int teamNum = 0;
    	if(StringHelper.isNotBlank(userId)){
    		//在用户表中寻找parent_id是该用户Id的用户
    		UsersMallExample example = new UsersMallExample();
    		com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andIdEqualTo(userId);
    		List<UsersMall> list = usersMallService.list(example);
    		if(list.size()>0){
    			String myteamOne = String.valueOf(list.get(0).getSuccessPeopleOne());
				String myteamTwo = String.valueOf(list.get(0).getSuccessPeopleTwo());
				if(myteamOne != "null" && myteamTwo != "null"){
					teamNum = list.get(0).getSuccessPeopleOne() + list.get(0).getSuccessPeopleTwo();
				}
				if(myteamOne != "null" && myteamTwo.equals("null")){
					teamNum = list.get(0).getSuccessPeopleOne();
				}
				if(myteamOne.equals("null") && myteamTwo != "null"){
					teamNum = list.get(0).getSuccessPeopleTwo();
				}
    		}
    	}
    	return teamNum;
    }
    
    //token是否有效
    public UsersMall getUsersByTokenAndAppId( String token, String appId ){
    	UsersMall result = null;
    	if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){
    		//验证TOKEN是否有效
    		UsersTokenExample example = new UsersTokenExample();
    		com.itic.mall.system.users.userstoken.persistence.model.UsersTokenExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);//是否有效
    		criteria.andAccessTokenEqualTo(token);//token是否一样
    		criteria.andAppIdEqualTo(appId);//appId是否一致
    		criteria.andIsOffsiteEqualTo(DBConst.FALSE);//是否异地登入
    		criteria.andExpiredTimeGreaterThanOrEqualTo(new Date());//是否过期
    		List<UsersToken> list = usersTokenService.list(example);
    		if( list.size()>0 ){
    			 UsersToken usersToken = list.get(0);
    			 result = usersMallService.get(usersToken.getUserId());
    		}
    	}
		return result;
    } 
    
     
    /*public UsersMall getUsersByTokenAndAppId( String token, String appId ){
    	UsersMall result = null;
    	if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){
    		//先到redis查找有没有
    		UsersMall user = loginRedisService.get(token+appId);
    		if( null != user ){
    			result = user;
    			//刷新用户token
   			 	loginRedisService.reflush(token+appId, result);
   			 	
    		}else{
    			//验证TOKEN是否有效
        		UsersTokenExample example = new UsersTokenExample();
        		com.itic.mall.system.users.userstoken.persistence.model.UsersTokenExample.Criteria criteria = example.createCriteria();
        		criteria.andIsEffectiveEqualTo(DBConst.TRUE);//是否有效
        		criteria.andAccessTokenEqualTo(token);//token是否一样
        		criteria.andAppIdEqualTo(appId);//appId是否一致
        		criteria.andIsOffsiteEqualTo(DBConst.FALSE);//是否异地登入
        		criteria.andExpiredTimeGreaterThanOrEqualTo(new Date());//是否过期
        		List<UsersToken> list = usersTokenService.list(example);
        		if( list.size()>0 ){
        			 UsersToken usersToken = list.get(0);
        			 result = usersMallService.get(usersToken.getUserId());
        			 //刷新用户token
        			 loginRedisService.reflush(token+appId, result);
        		}
    		}
    	}
		return result;
    } */
    
    public Usersaddress getUsersAddr(String userId,String addrId){
    	Usersaddress usersaddress = null;
    	if(StringHelper.isNotBlank(userId) && StringHelper.isNotBlank(addrId)){
    		UsersaddressExample example = new UsersaddressExample();
    		com.itic.mall.system.users.address.persistence.model.UsersaddressExample.Criteria criteria = example.createCriteria();
    		criteria.andIdEqualTo(addrId);
    		criteria.andUserIdEqualTo(userId);
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		List<Usersaddress> list = usersaddressService.list(example);
    		if(list.size()>0){
    			usersaddress = list.get(0);
    		}
    		
    	}
    	return usersaddress;
    }
    /**
     * 根据用户ID获取用户信息
     * @param userId
     * @return
     */
    public UsersMall getuserByUserId(String userId){
    	UsersMall result = null;
    	if(StringHelper.isNotBlank(userId)){
    		UsersMallExample example = new UsersMallExample();
    		com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andIdEqualTo(userId);
    		List<UsersMall> list = usersMallService.list(example);
    		if(list.size()>0){
    			result = list.get(0);
    		}
    	}
    	return result;
    }
    
    /**
     * 根据用户ID获取用户信息
     * @param userId
     * @return
     */
    public UsersMall getUserByInviteCode(String inviteCode){
    	UsersMall result = null;
    	if(StringHelper.isNotBlank(inviteCode)){
    		UsersMallExample example = new UsersMallExample();
    		com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andInvitingCodeEqualTo(inviteCode);
    		List<UsersMall> list = usersMallService.list(example);
    		if(list.size()>0){
    			result = list.get(0);
    		}
    	}
    	return result;
    }
    
    /**
     * 根据用户ID获取用户信息
     * @param userId
     * @return
     */
    public String getYunInviteCode(){
    	String randomNumStr = RandomStringHelper.randomNumStr(6);
    	UsersMall userByInviteCode = getUserByInviteCode(randomNumStr);
    	if( null != userByInviteCode){
    		return getYunInviteCode();
    	}else{
    		return randomNumStr;
    	}
    }
    /**
     * 预估收益7天转为实际收益（调用此方法之前要先确定对应记录的订单已确认收货）
     * @param userId
     * @param orderNo
     * @param skuId
     */
    public void PreToActaulBefore(String userId,String orderNo,String skuId){
		PayUserlog PrepayUserlog = getPayuserLog(userId,orderNo,skuId);
		if(PrepayUserlog != null){
			Date preTime = PrepayUserlog.getPayTime();
			Date date = new Date();
			long days = (date.getTime() - preTime.getTime())/1000*60*60*24;
			//预估收益7天以上
			if(days >7){
				//生成实际收益日志
				writePreProfitLog(PrepayUserlog.getSkuId(),PrepayUserlog.getOrderNo(),PrepayUserlog.getPayNo(),PrepayUserlog.getUserId(),PrepayUserlog.getType(),
						PrepayUserlog.getPayTime(),PrepayUserlog.getIncomeType(),PrepayUserlog.getPreAmount(),PrepayUserlog.getPreIncomeChannel(),
						PrepayUserlog.getPreIncomeType(),"002");
				//将预估收益日志置失效
				PrepayUserlog.setIsEffective(DBConst.FALSE);
				payUserlogService.edit(PrepayUserlog);
			}
		}
    }
    public void teamPretoActual(String userId,String orderNo,String skuId){
    	//给该云店主的上一级增加实际收益
		if(StringHelper.isNotBlank(userId)){
			PayUserlog onePrepayUserlog = getPayuserLog(userId,orderNo,skuId);
			//生成实际收益日志
			writePreProfitLog(onePrepayUserlog.getSkuId(),onePrepayUserlog.getOrderNo(),onePrepayUserlog.getPayNo(),onePrepayUserlog.getUserId(),onePrepayUserlog.getType(),
					onePrepayUserlog.getPayTime(),onePrepayUserlog.getIncomeType(),onePrepayUserlog.getPreAmount(),onePrepayUserlog.getPreIncomeChannel(),
					onePrepayUserlog.getPreIncomeType(),"002");
			//将预估收益日志置失效
			onePrepayUserlog.setIsEffective(DBConst.FALSE);
			payUserlogService.edit(onePrepayUserlog);
		}
		//给该云店主的上上一级增加预估收益
		String topParentId = getParentId(userId);
		if(StringHelper.isNotBlank(topParentId)){
			PayUserlog topPrepayUserlog = getPayuserLog(topParentId,orderNo,skuId);
			//生成实际收益日志
			writePreProfitLog(topPrepayUserlog.getSkuId(),topPrepayUserlog.getOrderNo(),topPrepayUserlog.getPayNo(),topPrepayUserlog.getUserId(),topPrepayUserlog.getType(),
					topPrepayUserlog.getPayTime(),topPrepayUserlog.getIncomeType(),topPrepayUserlog.getPreAmount(),topPrepayUserlog.getPreIncomeChannel(),
					topPrepayUserlog.getPreIncomeType(),"002");
			//将预估收益日志置失效
			topPrepayUserlog.setIsEffective(DBConst.TRUE);
			payUserlogService.edit(topPrepayUserlog);
		}
    }
    /**
     * 预估收益转为实际收益
     * @param userId
     * @param orderNo
     * @param skuId
     * @param ifAll
     */
    public void PreToActaul(String userId,String orderNo,String skuId){
    	if(StringHelper.isNotBlank(userId)){
    		UsersMall users = getuserByUserId(userId);
    		String userType = users.getType();
    		String parentId = users.getParentId();
    		String yunId = users.getYunId();
    		if(userType.equals("002")){
				//根据用户ID，订单号，商品ID获取预估收益日志，生成实际收益日志后将预估收益日志置于失效
    			PreToActaulBefore(userId,orderNo,skuId);
    			teamPretoActual(parentId,orderNo,skuId);
			}else{
				//普通用户给云店主增加实际收益
				if(StringHelper.isNotBlank(yunId)){
					//根据用户ID，订单号，商品ID获取预估收益日志，生成实际收益日志后将预估收益日志置于失效
					PreToActaulBefore(yunId,orderNo,skuId);
					//给该云店主的上一级增加预估收益
					String oneParentId = getParentId(yunId);
					teamPretoActual(oneParentId,orderNo,skuId);
				}
			}
    	}
    }
    /**
	 * 根据商品来源和商品Id获取商品信息
	 * @param type
	 * @param goodsId
	 * @return
	 */
	public StoreGoodsVo getstoreGoods(String userId,String goodsId){
		StoreGoodsVo storeGoodsVo = new StoreGoodsVo();		
		if(StringHelper.isNotBlank(goodsId) && StringHelper.isNotBlank(userId)){
			GoodsSpuExample example = new GoodsSpuExample();
	    	com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample.Criteria criteria = example.createCriteria();
	    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	    	criteria.andIdEqualTo(goodsId);
			List<GoodsSpu> list = goodsSpuService.list(example);
			if (list.size() > 0) {
				GoodsSpu goodsSpu = list.get(0);
				// 根据商品来源和商品ID封装商品信息
				// 根据商品ID获取优惠券金额
				double couponAmount = getCouponAmountByGoodsId(goodsId);
				storeGoodsVo.setCouponMoney(couponAmount);
				// 根据商品ID获取商品活动类型
				String activeType = getGoodsActive(goodsSpu);
				storeGoodsVo.setSpuPlatform(goodsSpu.getSpuPlatform());
				storeGoodsVo.setGoodsActive(activeType);
				storeGoodsVo.setMainImageUrl(goodsSpu.getMainImageUrl());
				storeGoodsVo.setGoodsName(goodsSpu.getGoodsName());
				// 在店铺表中获取是否以分享标志
				String isShared = getIsShared(goodsId, userId);
				storeGoodsVo.setIsShared(isShared);
				storeGoodsVo.setWlCommission(goodsSpu.getMarketProfit());
				storeGoodsVo.setPrice(goodsSpu.getPrice());
				storeGoodsVo.setConPrice(goodsSpu.getWlCommission());
				// 根据商品来源获取条幅图片
				String resType = goodsSpu.getGoodsSource();
				String scrollImg = getScrollImg(resType);
				storeGoodsVo.setScrollImg(scrollImg);
				int feeback = goodsSpu.getTotalFeedback()==null?0:goodsSpu.getTotalFeedback();
				storeGoodsVo.setTotalFeedback(feeback);
				int totalSale = goodsSpu.getTotalSales()==null?0:goodsSpu.getTotalSales();
				storeGoodsVo.setTotalSales(totalSale);
			}
		}
		return storeGoodsVo;
	}
	
	 /**
		 * 根据商品来源和商品Id获取商品信息
		 * @param type
		 * @param goodsId
		 * @return
		 */
		public StoreGoodsVo getHotGoods(String userId,String goodsId){
			StoreGoodsVo storeGoodsVo = new StoreGoodsVo();		
			if(StringHelper.isNotBlank(goodsId)){
				GoodsSpuExample example = new GoodsSpuExample();
		    	com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample.Criteria criteria = example.createCriteria();
		    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		    	criteria.andSpuNumEqualTo(goodsId);
		    	criteria.andIsHotEqualTo("1");
				List<GoodsSpu> list = goodsSpuService.list(example);
				if (list.size() > 0) {
					GoodsSpu goodsSpu = list.get(0);
					// 根据商品来源和商品ID封装商品信息
					// 根据商品ID获取优惠券金额
					double couponAmount = getCouponAmountByGoodsId(goodsId);
					storeGoodsVo.setCouponMoney(couponAmount);
					// 根据商品ID获取商品活动类型
					storeGoodsVo.setGoodsActive("003");
					storeGoodsVo.setMainImageUrl(goodsSpu.getMainImageUrl());
					storeGoodsVo.setGoodsName(goodsSpu.getGoodsName());
					// 在店铺表中获取是否以分享标志
					String isShared = getIsShared(goodsId, userId);
					storeGoodsVo.setIsShared(isShared);
					storeGoodsVo.setWlCommission(goodsSpu.getWlCommission());
					storeGoodsVo.setPrice(goodsSpu.getOrginPrice());
					storeGoodsVo.setConPrice(goodsSpu.getPrice());
					// 根据商品来源获取条幅图片
					String resType = goodsSpu.getGoodsSource();
					String scrollImg = getScrollImg(resType);
					storeGoodsVo.setScrollImg(scrollImg);
					int feeback = goodsSpu.getTotalFeedback()==null?0:goodsSpu.getTotalFeedback();
					storeGoodsVo.setTotalFeedback(feeback);
					int totalSale = goodsSpu.getTotalSales() ==null?0:goodsSpu.getTotalSales();
					storeGoodsVo.setTotalSales(totalSale);
					

				}
			}
			return storeGoodsVo;
		}
	/**
	 * 根据商品来源获取条幅图
	 * @param resType
	 * @return
	 */
	public String getScrollImg(String resType){
		String img = null;
		if(StringHelper.isNotBlank(resType)){
			ProjectStoreScrollExample example = new ProjectStoreScrollExample();
			com.itic.mall.system.project.storescroll.persistence.model.ProjectStoreScrollExample.Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andScrollIdEqualTo(resType);
			List<ProjectStoreScroll> list = projectStoreScrollService.list(example);
			if(list.size()>0){
				img = list.get(0).getScrollImg();
			}
		}
		return img;
	}
	/**
	 * 根据店铺商品ID查是否已分享
	 * @param goodsId
	 * @param userId
	 * @return
	 */
	public String getIsShared(String goodsId,String userId){
		String isShared = "0";
		if(StringHelper.isNotBlank(goodsId) && StringHelper.isNotBlank(userId)){
			UsersStoreExample example = new UsersStoreExample();
			com.itic.mall.system.users.store.persistence.model.UsersStoreExample.Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andUserIdEqualTo(userId);
			criteria.andGoodsIdEqualTo(goodsId);
			List<UsersStore> list = usersStoreService.list(example);
			if(list.size()>0){
				isShared = list.get(0).getIsShared();
			}
		}
		return isShared;
	}
	public String getGoodsActive(GoodsSpu goodsSpu){
		String activeType = null;
		//商品来源（001：秒杀，002：拼团,003:热卖，004：精品，005：特卖）
		if(goodsSpu != null){
			if(StringHelper.isNotBlank(goodsSpu.getIsHot())){
				activeType = "003";
			}
			if(StringHelper.isNotBlank(goodsSpu.getIsJingping())){
				activeType = "004";
			}
			if(StringHelper.isNotBlank(goodsSpu.getIsSpecial())){
				activeType = "005";
			}
		}
		return activeType;
	}
    //根据平台类别查询商品
    public List<GoodsSpu> getGoodsByPlatform(String platform){
    	GoodsSpuExample example = new GoodsSpuExample();
    	// 按创建时间倒序
    	example.setOrderByClause("create_time desc");
    	// 按排列号顺序
    	example.setOrderByClause("reorder asc");
    	
    	com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample.Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andSpuPlatformEqualTo(platform);
    	// 获取数据
    	List<GoodsSpu> list = goodsSpuService.list(example);
    	return list;
    }
    //根据手机号码查找用户信息
    public UsersMall getUsersByPhone( String phone ){
    	return usersMallService.getByPhone(phone);
    }
    
    public UsersMall getUsersByUnionid( String unionid ){
    	return usersMallService.getByUnionid(unionid);
    }
    
    public UsersMall getUsersByOpenid( String openid ){
    	return usersMallService.getByOpenid(openid);
    }
    
    /**
     * 获取轮播图信息 
     * @param type
     * @return
     */
    public List<Map<String, Object>> getMarketBannersByType(String type){
	    MarketBannerExample example = new MarketBannerExample();
   		example.setOrderByClause("REORDER ASC");
   		Criteria criteria = example.createCriteria(); 
   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
   		criteria.andIsVisibleEqualTo(DBConst.TRUE);
   		if( StringHelper.isNotBlank(type) ){
   			criteria.andTypeEqualTo(type);
   		}
   		List<MarketBanner> list = marketBannerService.list(example);
   		example = null;
   		List<Map<String, Object>> tranList2MapList = ValueHelper.tranList2MapList(list, new String[] {  "isVisible","createTime","createUser", "isEffective", "updateTime", "orgCode","reorder","note","name","type","url","title","content","catolog","model","banner"});
   		return tranList2MapList;
   }
    
    /** 
    * 获取广告位所有信息
    * @return
    */
   public List<Map<String, Object>> getMarketAdvertByTypeAndAddress(String type,String address){
	   MarketAdvertExample example = new MarketAdvertExample();
	   example.setOrderByClause("REORDER ASC");
	   com.itic.mall.system.market.marketadvert.persistence.model.MarketAdvertExample.Criteria criteria = example.createCriteria();
	   criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   criteria.andIsVisibleEqualTo(DBConst.TRUE);
	   
	  /* Date date = new Date();
	   criteria.andStartTimeLessThan(date);
	   criteria.andEndTimeGreaterThan(date);*/
	   
	   criteria.andTypeEqualTo(type);
	   criteria.andAddressEqualTo(address);
	   
	   List<MarketAdvert> tempList = marketAdvertService.list(example);
	   List<MarketAdvert> list = new ArrayList<MarketAdvert>();
	   if( tempList.size()>0 ){
		   for( MarketAdvert temp: tempList ){
			   boolean isStart = true;
			   boolean isEnd = true;
			   
			   Date now = new Date();
			   if( null != temp.getStartTime() ){
				   isStart = DateHelper.isGreaterDate(now, temp.getStartTime());
			   }
			   if( null != temp.getEndTime() ){
				   isEnd = DateHelper.isGreaterDate(temp.getEndTime(), now);
			   }
			   if( isStart && isEnd ){
				   list.add(temp);
			   }
		   }
	   }
	   
	   List<Map<String, Object>> tranList2MapList = ValueHelper.tranList2MapList(list, new String[] {"isVisible","createTime","createUser", "isEffective", "updateTime", "orgCode","reorder","note","address","pdge","topTitle","subTitle","name","startTime","endTime","type","banner"});
	   return tranList2MapList;
   }
    
    /**
     * 获取轮播图信息
     * @param type
     * @return
     */
    public List<GrouponBanner> getGrouponBannersByType(String type){
    	GrouponBannerExample example = new GrouponBannerExample();
   		example.setOrderByClause("REORDER ASC");
   		com.itic.mall.system.groupon.banner.persistence.model.GrouponBannerExample.Criteria criteria = example.createCriteria(); 
   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
   		criteria.andIsVisibleEqualTo(DBConst.TRUE);
   		if( StringHelper.isNotBlank(type) ){
   			criteria.andTypeEqualTo(type);
   		}
   		List<GrouponBanner> list = grouponBannerService.list(example);
   		example = null;
   		return list;
   }
    
    public double getCreateMoney( UsersMall user ){
    	return 1.11;
    }
    
    public String getUpOrDown( UsersMall user ){
    	return "up";
    };
    
    public Jdset getJdset(){
    	Jdset jdset = null;
    	JdsetExample example = new JdsetExample();
    	com.itic.mall.system.project.jdset.persistence.model.JdsetExample.Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	String orgCode = PropertyHelper.getString("org.code");
    	criteria.andOrgCodeEqualTo(orgCode);
    	List<Jdset> list = jdsetService.list(example);
    	if( list.size()>0 ){
    		jdset = list.get(0);
    	}
    	return jdset;
    }
    /**
     * 获取订单项描述
     * @param orderNo
     * @param skuId
     * @return
     */
    public String getOrdersItemDesc(String orderNo,String skuId){
    	String itemDesc = null;
    	if(StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(skuId)){
    		OrdersItemExample exampleg = new OrdersItemExample();
    		com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg
    				.createCriteria();
    		criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteriag.andOrderNoEqualTo(orderNo);
    		criteriag.andGoodsIdEqualTo(skuId);
    		List<OrdersItem> listg = ordersItemService.list(exampleg);
    		if(listg.size()>0){
    			itemDesc = listg.get(0).getGoodsName();
    		}
    	}
    	return itemDesc;
    }
    /**
     * 获取整个订单描述
     * @param orderNo
     * @return
     */
	public String getDescByOrderNo(String orderNo) {
		String orderDesc = null;
		// 商品信息
		OrdersItemExample exampleg = new OrdersItemExample();
		com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg
				.createCriteria();
		criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
		criteriag.andOrderNoEqualTo(orderNo);
		List<OrdersItem> listg = ordersItemService.list(exampleg);
		int count = 0;
		if (listg.size() > 0) {
			for(OrdersItem ordersItem:listg){
				count++;
				if(listg.size() == count){
					if(orderDesc != null){
						orderDesc = orderDesc + ordersItem.getGoodsName();
					}else{
						orderDesc = ordersItem.getGoodsName();
					}
				}else{
					if(orderDesc != null){
						orderDesc = orderDesc + ordersItem.getGoodsName()+",";
					}else{
						orderDesc = ordersItem.getGoodsName()+",";
					}
				}
				
			}
		}
		return orderDesc;
	}
	
	/**
	 * 根据订单号和订单状态获取订单信息
	 * @param orderNo
	 * @return
	 */
    public OrdersDetail getOrderByOrderNo(String userId,String orderNo,String state){
    	OrdersDetail ordersDetail = null;
    	//订单信息
		OrdersDetailExample example = new OrdersDetailExample();
		com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample.Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andOrderNoEqualTo(orderNo);
		criteria.andUserIdEqualTo(userId);
		criteria.andStateEqualTo(state);//订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
		List<OrdersDetail> list = ordersDetailService.list(example);
		if(list.size()>0){
			ordersDetail = list.get(0);
		}
		return ordersDetail;
    }
    /**
     * 根据订单号获取订单项
     * @param orderNo
     * @return
     */
    public List<OrdersItem> getorderItem(String orderNo){
    	List<OrdersItem> itemList = new ArrayList<OrdersItem>();
    	if(StringHelper.isNotBlank(orderNo)){
    		OrdersItemExample exampleg = new OrdersItemExample();
			com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg.createCriteria();
			criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
			criteriag.andOrderNoEqualTo(orderNo);
			List<OrdersItem> list = ordersItemService.list(exampleg);
			if(list.size()>0){
				itemList = list;
			}
    	}
    	return itemList;
    }
    /**
     * 根据订单号和商品号获取订单详情
     * @param orderNo
     * @param goodsId
     * @return
     */
    public OrdersItem getorderItem(String orderNo,String goodsId){
    	OrdersItem ordersItem = new OrdersItem();
    	if(StringHelper.isNotBlank(goodsId) && StringHelper.isNotBlank(orderNo)){
    		OrdersItemExample exampleg = new OrdersItemExample();
			com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg.createCriteria();
			criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
			criteriag.andOrderNoEqualTo(orderNo);
			criteriag.andGoodsIdEqualTo(goodsId);
			List<OrdersItem> list = ordersItemService.list(exampleg);
			if(list.size()>0){
				ordersItem = list.get(0);
			}
    	}
    	return ordersItem;
    }
    /**
     * 根据订单号和商品号获取商品个数
     * @param orderNo
     * @param goodsId
     * @return
     */
    public int getCountByOrderNoandgoodsId(String orderNo,String goodsId){
    	int count = 0;
    	if(StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(goodsId)){
    		//订单信息
        	OrdersItemExample example = new OrdersItemExample();
        	com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteria = example.createCriteria();
        	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        	criteria.andOrderNoEqualTo(orderNo);
        	criteria.andGoodsIdEqualTo(goodsId);
        	List<OrdersItem> list = ordersItemService.list(example);
    		if(list.size()>0){
    			count = list.get(0).getCount();
    		}
    	}
		return count;
    }
    
    /**
     * 根据订单号和商品号获取商品信息
     * @param orderNo
     * @param goodsId
     * @return
     */
    public GoodsDetailVo getGoodsDetailByOrderNoandgoodsId(String orderNo,String goodsId){
    	GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
    	if(StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(goodsId)){
    		//订单信息
        	OrdersItemExample example = new OrdersItemExample();
        	com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteria = example.createCriteria();
        	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        	criteria.andOrderNoEqualTo(orderNo);
        	criteria.andSkuIdEqualTo(goodsId);
        	List<OrdersItem> list = ordersItemService.list(example);
    		if(list.size()>0){
    			goodsDetailVo.setCount(list.get(0).getCount());
    			goodsDetailVo.setGoodsImg(list.get(0).getGoodsImg());
    			goodsDetailVo.setGoodsName(list.get(0).getGoodsName());
    			goodsDetailVo.setOrginPrice(list.get(0).getOrginPrice()==null?0:list.get(0).getOrginPrice());
    			Map<String,Object> paramMap = this.goodsSkuService.getGoodSkuById(list.get(0).getSkuId());
    			goodsDetailVo.setParam(paramMap);
    			goodsDetailVo.setPrice(list.get(0).getPrice());
    		}
    	}
		return goodsDetailVo;
    }
    
	public String getUserNameByOrderNo(String orderNo) {
		String userName = null;
		// 订单信息
		OrdersDetailExample example = new OrdersDetailExample();
		com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample.Criteria criteria = example
				.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andOrderNoEqualTo(orderNo);
		List<OrdersDetail> list = ordersDetailService.list(example);
		if(list.size()>0){
			userName = list.get(0).getUserNickName();
		}
		return userName;
	}
       
    /**
	 * 根据订单号和订单状态获取订单信息
	 * @param orderNo
	 * @return
	 */
    public OrdersDetail getOrderByAfterState(String orderNo,String afterstate){
    	OrdersDetail ordersDetail = new OrdersDetail();
    	//订单信息
		OrdersDetailExample example = new OrdersDetailExample();
		com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample.Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andOrderNoEqualTo(orderNo);
		criteria.andAfterSaleStateEqualTo(afterstate);//售后状态（1.在售后申请期内，2.超过售后申请期限，3.售后申请中，4.已处理售后申请）
		List<OrdersDetail> list = ordersDetailService.list(example);
		if(list.size()>0){
			ordersDetail = list.get(0);
		}
		return ordersDetail;
    }
    
    public OrdersItem getOrderByAfterState(String orderNo,String skuId,String afterstate){
    	OrdersItem ordersItem = new OrdersItem();
    	//订单信息
		OrdersDetailExample example = new OrdersDetailExample();
		com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample.Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andOrderNoEqualTo(orderNo);
		criteria.andAfterSaleStateEqualTo(afterstate);//售后状态（1.在售后申请期内，2.超过售后申请期限，3.售后申请中，4.已处理售后申请）
		List<OrdersDetail> list = ordersDetailService.list(example);
		if(list.size()>0){
			OrdersItemExample itemexample = new OrdersItemExample();
			com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriaitem = itemexample.createCriteria();
			criteriaitem.andIsEffectiveEqualTo(DBConst.TRUE);
			criteriaitem.andOrderNoEqualTo(orderNo);
			criteriaitem.andGoodsIdEqualTo(skuId);
			List<OrdersItem> listitem = ordersItemService.list(itemexample);
			if(listitem.size()>0){
				ordersItem = listitem.get(0);
			}
		}
		return ordersItem;
    }
    /**
     * 根据售后状态获取对应的描述
     * @param state
     * @return
     */
    public String getDescribeByState(String state){
    	String describe = null;
    	if(StringHelper.isNotBlank(state)){
    		ProjectDescribeExample example = new ProjectDescribeExample();
    		com.itic.mall.system.project.describe.persistence.model.ProjectDescribeExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andStateEqualTo(state);
    		List<ProjectDescribe> list = projectDescribeService.list(example);
    		if(list.size()>0){
    			describe = list.get(0).getContent();
    		}
    	}
    	return describe;
    }
    
    /**
     * 根据原因类型获取对应的描述列表
     * @param reasonType
     * @param state
     * @return
     */
    public List<String> getDescribeType(String reasonType){
    	String describe = null;
    	List<String> desclist = new ArrayList<String>();
    	if(StringHelper.isNotBlank(reasonType)){
    		ProjectDescribeExample example = new ProjectDescribeExample();
    		com.itic.mall.system.project.describe.persistence.model.ProjectDescribeExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andReasonTypeEqualTo(reasonType);
    		List<ProjectDescribe> list = projectDescribeService.list(example);
    		if(list.size()>0){
    			for(ProjectDescribe projectDescribe:list){
        			describe = projectDescribe.getContent();
        			desclist.add(describe);
    			}
    		}
    	}
    	return desclist;
    }
    
    /**
     * 根据原因类型获取对应的描述
     * @param reasonType
     * @param state
     * @return
     */
    public String getNameByType(String reasonType){
    	String describe = null;
    	if(StringHelper.isNotBlank(reasonType)){
    		ProjectDescribeExample example = new ProjectDescribeExample();
    		com.itic.mall.system.project.describe.persistence.model.ProjectDescribeExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andReasonTypeEqualTo(reasonType);
    		List<ProjectDescribe> list = projectDescribeService.list(example);
    		if(list.size()>0){
    			describe = list.get(0).getContent();
    		}
    	}
    	return describe;
    }
    
    /**
     * 根据原因类型获取对应的描述列表
     * @param reasonType
     * @param state
     * @return
     */
	public List<Map<String, Object>> getexpresslist(HttpServletRequest request, HttpServletResponse response) {
		String companyNo = null;
		String companyName = null;
		List<Map<String, Object>> desclist = new ArrayList<Map<String, Object>>();
		ProjectExpressExample example = new ProjectExpressExample();
		com.itic.mall.system.project.proexpress.persistence.model.ProjectExpressExample.Criteria criteria = example
				.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		List<ProjectExpress> list = projectExpressService.list(example);
		if (list.size() > 0) {
			for (ProjectExpress projectExpress : list) {
				companyName = projectExpress.getExpressCompany();
				companyNo = projectExpress.getExpressCompanyNo();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("companyName", companyName);
				map.put("companyNo", companyNo);
				desclist.add(map);
			}
		}

		return desclist;
	}
	public String getParentId(String userId){
		String parentId = null;
		if(StringHelper.isNotBlank(userId)){
			UsersMallExample example = new UsersMallExample();
			com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample .Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andIdEqualTo(userId);
			List<UsersMall> list = usersMallService.list(example);
			if(list.size()>0){
				parentId = list.get(0).getParentId();
			}
		}
		return parentId;
	}
    /**
     * 根据订单号处理订单支付业务逻辑
     * @param orderNo
     * @return
     */
    public String dealOrderByorderNo(String orderNo,String payNo,Date payTime,String payType){
    	String result = FAIL;
    	//处理订单信息
		OrdersDetailExample example = new OrdersDetailExample();
		com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample.Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andOrderNoEqualTo(orderNo);
		criteria.andStateEqualTo("1");//订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
		List<OrdersDetail> list = ordersDetailService.list(example);
		if(list.size()>0){
			String userId = list.get(0).getUserId();
			//获取邀请人ID
			String parentId = getParentId(userId);
			String userType = list.get(0).getType();
			String yunId = list.get(0).getYunUserId();
			String couponId = list.get(0).getCouponId();//优惠券ID是多个用户逗号隔开拼接的
			String isUsePoinst = list.get(0).getIsUsePoints();
			Double sumAmount = list.get(0).getSumAmount();
			list.get(0).setState("3");
			result = ordersDetailService.edit(list.get(0));
			//处理用户订单项
			OrdersItemExample exampleItem = new OrdersItemExample();
			com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriaItem = exampleItem.createCriteria();
			criteriaItem.andIsEffectiveEqualTo(DBConst.TRUE);
			criteriaItem.andOrderNoEqualTo(orderNo);
			List<OrdersItem> listItem = ordersItemService.list(exampleItem);
			if(listItem.size()>0){
				for(OrdersItem ordersItem:listItem){
					ordersItem.setState("3");
					result = ordersItemService.edit(ordersItem);
					if(SUCCESS.equals(result)){
						if(SUCCESS.equals(result)){
							//处理用户惠金币
							if(StringHelper.isNotBlank(isUsePoinst) && "1".equals(isUsePoinst)){
								result =dealUsersPoints(orderNo,userId);
							}
							//处理用户券信息
							if(SUCCESS.equals(result)){
								if(StringHelper.isNotBlank(couponId)){
									result = dealCoupon(couponId,userId);
									//用户支付表中记录花钱日志
									if(SUCCESS.equals(result)){
										PayUserlog payUserlog = new PayUserlog();
										payUserlog.setAmount(sumAmount);
										//余额支付处理可用余额
								    	payUserlog.setBalance(100.0);//可用余额
								    	payUserlog.setSkuId("");
								    	payUserlog.setOrderNo(orderNo);
								    	payUserlog.setPayNo(payNo);
								    	payUserlog.setUserId(userId);
								    	payUserlog.setType("002");//账务类型（001：收入，002：支出,003:提现）
								    	payUserlog.setPayType(payType);//支付类型（001：支付宝，002：微信，003：余额）
								    	payUserlog.setPayTime(payTime);
										result = writePayLog(payUserlog);
									}
									//每个订单项记录一个预估收益日志
									//该用户为云店主用户时，支付日志表中记录预估收益日志
									if(StringHelper.isNotBlank(userType) && "002".equals(userType)){
										//云用户自己的预估收益
										writePreProfitLog(orderNo,ordersItem.getGoodsId(),payNo,userId,"001",payTime,"001",ordersItem.getActualPay(),"C001","PI001","001");
										//给该云店主的上一级增加预估收益
										if(StringHelper.isNotBlank(parentId)){
											writePreProfitLog(orderNo,ordersItem.getGoodsId(),payNo,parentId,"001",payTime,"001",ordersItem.getActualPay(),"C001","PI001","001");
										}
										//给该云店主的上上一级增加预估收益
										/*
										String topParentId = getParentId(parentId);
										if(StringHelper.isNotBlank(topParentId)){
											writePreProfitLog(orderNo,ordersItem.getGoodsId(),payNo,topParentId,"001",payTime,"001",ordersItem.getActualPay(),"C001","PI001","001");
										}
										*/
									}
									//该用户为普通用户，云店主ID不为空时，给云店主记录预估收益日志
									if(StringHelper.isNotBlank(userType) && "001".equals(userType) && StringHelper.isNotBlank(yunId)){
										//给云店主记录预估收益日志
										writePreProfitLog(orderNo,ordersItem.getGoodsId(),payNo,yunId,"001",payTime,"001",ordersItem.getActualPay(),"C001","PI001","001");
										//给该云店主的上一级增加预估收益
										String oneParentId = getParentId(yunId);
										if(StringHelper.isNotBlank(oneParentId)){
											writePreProfitLog(orderNo,ordersItem.getGoodsId(),payNo,oneParentId,"001",payTime,"001",ordersItem.getActualPay(),"C001","PI001","001");
											//给该云店主的上上一级增加预估收益
											/*
											String topParentId = getParentId(oneParentId);
											if(StringHelper.isNotBlank(topParentId)){
												writePreProfitLog(orderNo,ordersItem.getGoodsId(),payNo,topParentId,"001",payTime,"001",ordersItem.getActualPay(),"C001","PI001","001");
											}
											*/
										}									
									}
									//确认更新用户总消费金额
								}
							}
						}
					}
				}
			}	
		}
		return result;
    }
  //根据用户ID，订单号，商品ID获取预估收益日志，生成实际收益日志后将预估收益日志置于失效
    public PayUserlog getPayuserLog(String userId,String orderNo,String skuId){
    	PayUserlog payUserlog = null;
    	if(StringHelper.isNotBlank(userId) && StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(skuId)){
    		PayUserlogExample example = new PayUserlogExample();
    		com.itic.mall.system.pay.userlog.persistence.model.PayUserlogExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andUserIdEqualTo(userId);
    		criteria.andOrderNoEqualTo(orderNo);
    		criteria.andSkuIdEqualTo(skuId);
    		List<PayUserlog> list = payUserlogService.list(example);
    		if(list.size()>0){
    			payUserlog = list.get(0);
    		}
    	}
    	return payUserlog;
    }
    /**
     * 查订单下的所有订单项是否已确认收货且时间已过七天
     * @param orderNo
     * @param state
     * @return
     */
    public boolean getOrderItemState(String orderNo,String state){
    	boolean ifAll = false;
    	OrdersItemExample example = new OrdersItemExample();
    	com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andOrderNoEqualTo(orderNo);
    	List<OrdersItem> list = ordersItemService.list(example);
    	if(list.size()>0){
    		for(OrdersItem ordersItem:list){
    			if(!(ordersItem.getState().equals(state) || ordersItem.getState().equals("6"))){
    				ifAll = false;
    				break;
    			}else{
    				ifAll = true;
    			}
    		}
    	}
    	return ifAll;
    }
    /**
     * 修改订单状态和结束时间
     * @param orderNo
     * @param state
     */
    public void modifyOrderState(String orderNo,String state){
    	if(StringHelper.isNotBlank(orderNo)){
    		OrdersDetail ordersDetail = getOrderdetail(orderNo);
    		if(ordersDetail != null){
    			Date endTime = new Date();
    			ordersDetail.setState(state);
    			ordersDetail.setEndTime(endTime);
    			ordersDetailService.edit(ordersDetail);
    		}
    	}
    }
    /**
     * 根据订单号获取订单
     * @param orderNo
     * @return
     */
    public OrdersDetail getOrderdetail(String orderNo){
    	OrdersDetail ordersDetail = null;
    	if(StringHelper.isNotBlank(orderNo)){
    		OrdersDetailExample example = new OrdersDetailExample();
    		com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andOrderNoEqualTo(orderNo);
    		List<OrdersDetail> list = ordersDetailService.list(example);
    		if(list.size()>0){
    			ordersDetail = list.get(0);
    		}
    	}
    	return ordersDetail;
    }
    public List<OrdersDetail> getOrderBystate(String state){
    	List<OrdersDetail> list = null;
    	if(StringHelper.isNotBlank(state)){
    		OrdersDetailExample example = new OrdersDetailExample();
    		com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andStateEqualTo(state);
    		list = ordersDetailService.list(example);
    	}
    	return list;
    }
    /**
     * 预估转实际收益，增加云店主订单数
     */
    public void pretoActualandAddOrderCount(){
    	//查询所有已经确认收货的订单
    	List<OrdersDetail> list = getOrderBystate("5");
    	pretoActualAndaddOrder(list);
    	//查询所有已经评价的订单
    	List<OrdersDetail> lists = getOrderBystate("6");
    	pretoActualAndaddOrder(lists);
    }
    /**
     * 预估转实际收益，增加云店主订单数
     * @param list
     */
    public void pretoActualAndaddOrder(List<OrdersDetail> list){
    	for(OrdersDetail ordersDetail:list){
    		String orderNo = ordersDetail.getOrderNo();
    		String userId = ordersDetail.getUserId();
    		List<OrdersItem> listItem = getOrderItem(orderNo); 
    		//每个订单项预估收益转为实际收益
    		for(OrdersItem ordersItem:listItem){
    			String skuId = ordersItem.getGoodsId();
        		PreToActaul(userId,orderNo,skuId);
    		}
    	}
    }
    /**
     * 云店主成交订单量增加
     * @param orderNo
     */
    public void addOrderCount(String orderNo){
    	//获取订单信息
    	OrdersDetail ordersDetail = getOrderdetail(orderNo);
    	Double sumAmount = ordersDetail.getSumAmount();
    	Date endTime = ordersDetail.getEndTime();
    	Date date = new Date();
    	long days = (date.getTime() - endTime.getTime())/1000*60*60*24;
    	//订单确认收货大于等于七天算成功一单,总消费金额也加上
    	if(days>=7){
    		String userId = ordersDetail.getUserId();
        	String userType = null;
    		String yunId = null;
    		Integer yunDealedOrder = null;
        	//获取用户信息
    		UsersMall usersMall = getuserByUserId(userId);
    		if(usersMall != null){
    			userType = usersMall.getType();
    			yunId = usersMall.getYunId();
    			if(StringHelper.isNotBlank(userType)){
    				if(userType.equals("002")){
    					yunDealedOrder = usersMall.getYunDealedOrder();
    					usersMall.setTotalComsum(sumAmount);
    					usersMall.setYunDealedOrder(yunDealedOrder+1);
    					usersMallService.edit(usersMall);
    				}
    				if(userType.equals("001")){
    					if(StringHelper.isNotBlank(yunId)){
    						UsersMall users = getuserByUserId(yunId);
    						yunDealedOrder = users.getYunDealedOrder();
        					usersMall.setTotalComsum(sumAmount);
    						usersMall.setYunDealedOrder(yunDealedOrder+1);
    						usersMallService.edit(usersMall);
    					}
    				}
    			}
    		}
    	}   	
    }
    /**
     * 根据订单号获取用户支付日志
     * @param orderNo
     * @return
     */
    public PayUserlog getPayuserLog(String orderNo){
    	PayUserlog payUserlog = null;
    	if(StringHelper.isNotBlank(orderNo)){
    		PayUserlogExample example = new PayUserlogExample();
    		com.itic.mall.system.pay.userlog.persistence.model.PayUserlogExample.Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andOrderNoEqualTo(orderNo);
    		List<PayUserlog> list = payUserlogService.list(example);
    		if(list.size()>0){
    			payUserlog = list.get(0);
    		}
    	}
    	return payUserlog;
    }
    /**
     * 当前时间超过确认收货失效时间，默认确认收货
     */
	public void confirmOrder() {
		String result = FAIL;
		// 查询所有待支付订单
		List<OrdersDetail> list = getOrderBystate("1");
		if (list.size() > 0) {
			for (OrdersDetail Orders : list) {
				String orderNo = Orders.getOrderNo();
				OrdersDetail ordersDetail = getOrderdetail(orderNo);
				if (ordersDetail != null) {
					Date startTime = ordersDetail.getStartTime();
					Date date = new Date();
					long expire = date.getTime() - startTime.getTime();
					long expireTime = ordersDetail.getReceiveExpireTime()* 1000 * 60 * 60;
					// 超过支付失效时间则将订单置失效
					if (expire > expireTime) {
						ordersDetail.setState("5");
						result = ordersDetailService.edit(ordersDetail);
						if (SUCCESS.equals(result)) {
							confirmOrderItems(orderNo);
						}
					}
				}
			}
		}
	}
	/**
	 * 订单项自动确认收货
	 * @param orderNo
	 */
	public void confirmOrderItems(String orderNo) {
		if (StringHelper.isNotBlank(orderNo)) {
			List<OrdersItem> list = getOrderItem(orderNo);
			if (list.size() > 0) {
				for (OrdersItem ordersItem : list) {
					ordersItem.setState("5");
					ordersItemService.edit(ordersItem);
				}
			}
		}
	}
    /**
     * 当前时间超过订单有效支付时间，将订单置失效
     * 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价，6.已评价，7：换货中，8：换货成功，9：退货中，10：退货成功，11：维修中，12：维修成功，13：退款中，14：退款成功）
     */
    public void expireOrderPay(){
    	String result = FAIL;
    	//查询所有待支付订单
		List<OrdersDetail> list = getOrderBystate("1");
		if(list.size()>0){
			for(OrdersDetail Orders:list){
				String orderNo = Orders.getOrderNo();
				OrdersDetail ordersDetail = getOrderdetail(orderNo);
		    	if(ordersDetail != null){
		    		Date startTime = ordersDetail.getStartTime();
		    		Date date = new Date();
		    		long expire = date.getTime() - startTime.getTime();
		    		long expireTime = ordersDetail.getPayExpireTime()*1000*60*60;
		    		//超过支付失效时间则将订单置失效
		    		if(expire>expireTime){
		    			ordersDetail.setIsEffective(DBConst.FALSE);
		    			result = ordersDetailService.edit(ordersDetail);
		    			if(SUCCESS.equals(result)){
		    				expireOrderItems(orderNo);
		    			}
		    		}
		    	}
			}
		}
    }
    /**
     * 当前时间超过订单有效支付时间，将订单置失效
     * 订单项置失效
     * @param orderNo
     */
    public void expireOrderItems(String orderNo){
    	if(StringHelper.isNotBlank(orderNo)){
	    	List<OrdersItem> list = getOrderItem(orderNo);
	    	if(list.size()>0){
	    		for(OrdersItem ordersItem:list){
	    			ordersItem.setIsEffective(DBConst.FALSE);
	    			ordersItemService.edit(ordersItem);
	    		}
	    	}
    	}
    }
    
    public List<OrdersItem> getOrderItem(String orderNo){
    	List<OrdersItem> list = null;
    	if(StringHelper.isNotBlank(orderNo)){
    		OrdersItemExample example = new OrdersItemExample();
	    	com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteria = example.createCriteria();
	    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	    	criteria.andOrderNoEqualTo(orderNo);
	    	list = ordersItemService.list(example);
    	}
    	return list;
    }
    /**
     * 预估收益记录
     * @param orderNo
     * @param payNo
     * @param userId
     * @param Type
     * @param payTime
     * @param incomeType
     * @param preAmount
     * @param incomeChannel
     * @param preIncomeType
     * @param preType
     */
    public void writePreProfitLog(String orderNo,String goodsId,String payNo,String userId,String Type,Date payTime,String incomeType,Double preAmount,
    		String incomeChannel,String preIncomeType,String preType){
    	PayUserlog payUserlog = new PayUserlog();
		payUserlog.setSkuId(goodsId);
    	payUserlog.setOrderNo(orderNo);
    	payUserlog.setPayNo(payNo);
    	payUserlog.setUserId(userId);
    	payUserlog.setType(Type);//账务类型（001：收入，002：支出,003:提现）
    	payUserlog.setPayTime(payTime);//yaogai
    	payUserlog.setIncomeType(incomeType);//收入类型(001:友惠钱包利息，002：京东联盟返利)
    	payUserlog.setPreAmount(preAmount);
    	payUserlog.setPreIncomeChannel(incomeChannel);//预估收益渠道(C001：京选友惠，C002：天猫，C003：淘宝，C004：京东)
    	payUserlog.setPreIncomeType(preIncomeType);//预估收益类型（PI001：佣金，PI002：提成）
    	payUserlog.setPreType(preType);//预估标识（001：预估，002：实际）
    	payUserlogService.add(payUserlog);
    }
    /**
     * 用户总消费增减
     * @param userId
     * @param type(add：增加,reduce：减少)
     * @param amount
     */
    public void addTotalConsume(String userId,String type,Double amount){
    	if(StringHelper.isNotBlank(userId) && StringHelper.isNotBlank(type)){
    		Double totalConsume = null;
    		UsersMallExample example = new UsersMallExample();
			com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample .Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andIdEqualTo(userId);
			List<UsersMall> list = usersMallService.list(example);
			if(list.size()>0){
				totalConsume = list.get(0).getTotalComsum();
				if(type.equals("add")){
					totalConsume = totalConsume + amount;
				}else{
					totalConsume = totalConsume - amount;
				}
				list.get(0).setTotalComsum(totalConsume);
				usersMallService.edit(list.get(0));
			}
    	}
    }
    public String writePayLog(PayUserlog payUserlogs){
    	String result = FAIL;
    	PayUserlog payUserlog = new PayUserlog();
    	payUserlog.setAmount(payUserlogs.getAmount()==null ?0:payUserlogs.getAmount());
    	payUserlog.setBalance(payUserlogs.getBalance());
    	payUserlog.setExpendType(payUserlogs.getExpendType());//支出类型(W001:支付宝提现，W002:微信提现)
    	payUserlog.setSkuId(payUserlogs.getSkuId());
    	payUserlog.setOrderNo(payUserlogs.getOrderNo());
    	payUserlog.setPayNo(payUserlogs.getPayNo());
    	payUserlog.setUserId(payUserlogs.getUserId());
    	payUserlog.setType(payUserlogs.getType());//账务类型（001：收入，002：支出,003:提现）
    	payUserlog.setPayType(payUserlogs.getPayType());//支付类型（001：支付宝，002：微信，003：公众号）
    	payUserlog.setPayTime(payUserlogs.getPayTime());
    	payUserlog.setIncomeType(payUserlogs.getIncomeType());//收入类型(001:友惠钱包利息，002：京东联盟返利)
    	payUserlog.setPreAmount(payUserlogs.getPreAmount()==null?0:payUserlogs.getPreAmount());
    	payUserlog.setPreIncomeChannel(payUserlogs.getPreIncomeChannel());
    	payUserlog.setPreIncomeType(payUserlogs.getPreIncomeType());//预估收益类型（PI001：佣金，PI002：提成）
    	payUserlog.setPreType(payUserlogs.getPreType());//预估标识（001：预估，002：实际）
    	payUserlog.setWithdrawFailReason(payUserlogs.getWithdrawFailReason());
    	payUserlog.setWithdrawFee(payUserlogs.getWithdrawFee()==null?0:payUserlogs.getWithdrawFee());
    	payUserlog.setWithdrawRemind(payUserlogs.getWithdrawRemind());
    	payUserlog.setWithdrawState(payUserlogs.getWithdrawState());//提现状态（0：失败，1：成功）
    	payUserlog.setWithdrawTotalAmount(payUserlogs.getWithdrawTotalAmount()==null?0:payUserlogs.getWithdrawTotalAmount());
    	result = payUserlogService.add(payUserlog);
    	return result;
    }
    /**
     * 订单支付时若有积分抵扣，处理积分抵扣逻辑
     * @param orderNo
     * @param userId
     * @param points
     * @return
     */
    public String dealUsersPoints(String orderNo,String userId){
    	String result = FAIL;
    	int points = 0;
    	//用户积分日志表最后一条中的积分数和积分可抵扣金额与此次抵扣做相减
    	UsersPointslogExample example = new UsersPointslogExample();
    	double pointsAmount = 0;
    	com.itic.mall.system.users.pointslog.persistence.model.UsersPointslogExample.Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andUserIdEqualTo(userId);
    	List<UsersPointslog> list = usersPointslogService.list(example);
    	if(list.size()>0){
    		//将当前的日志记录表数据置为失效
    		UsersPointslog usersPointslog = list.get(0);
    		points = usersPointslog.getPoints() - usersPointslog.getPoints();
    		pointsAmount = usersPointslog.getPointsAmount() - usersPointslog.getPointsAmount();
    		UsersPointslog usersPoints = null;
    		usersPointslog.setIsEffective(DBConst.FALSE);
    		result = usersPointslogService.edit(usersPointslog);
    		if(SUCCESS.equals(result)){    			
        		//减少后剩余的积分添加一份日志
        		usersPoints = new UsersPointslog();
        		usersPoints.setPoints(points);
        		usersPoints.setPointsAmount(pointsAmount);
        		usersPoints.setUserId(userId);
        		usersPoints.setOrderNo(orderNo);
        		usersPoints.setType("002");
        		usersPoints.setChangeReason(PointsChangeReason.reduce.getType());
        		result = usersPointslogService.add(usersPoints);
    		}   		
    	}else{
    		result = SUCCESS;
    	}		
    	return result;
    }
    
	   /**
		 * 根据SkuID获取商品信息
		 * @param request
		 * @param response
		 * @param token
		 * @param appId
		 * @param goodsId
		 * @return
		 */
		public GoodsDetailVo getGoodsDetailBySkuId(String skuId,int count) {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			String errorCode = PARAM_ERROR_CODE;
			String errorMsg = PARAM_ERROR_MSG;
			GoodsDetailVo Vo = new GoodsDetailVo();
			try{
				if(StringHelper.isNotBlank(skuId)){
					GoodsSpu goodsSpu = this.goodsSpuService.getBySku(skuId);
					Vo.setGoodsImg(goodsSpu.getMainImageUrl());// 图片  
					Vo.setGoodsName(goodsSpu.getGoodsName());// 名称
					Vo.setPrice(goodsSpu.getPrice());
					Vo.setOrginPrice(goodsSpu.getOrginPrice()==null?0:goodsSpu.getOrginPrice());
					Vo.setCount(count);
					Vo.setGoodsId(skuId);
					// 商品规格属性
					Map<String, Object> paramMap =this.goodsSkuService.getGoodSkuById(skuId);
					Vo.setParam(paramMap);// 商品规格参数
					resultMap.put("goodsData", Vo);
				}
			}catch(Exception e){
				errorCode = SERVER_ERROR_CODE;
				errorMsg = SERVER_ERROR_MSG;
				logException(errorCode, errorMsg, e.toString(), "根据商品ID获取商品信息", e);
			}
			return Vo;
			}
		/**
		 * 支付后处理用户优惠券
		 * @param couponIdstr
		 * @return
		 */
	public String dealCoupon(String couponIdstr,String userId) {
		String result = FAIL;
		String[] couponIds = null;
		try {
			couponIds = couponIdstr.split(",");
			for (int i = 0; i < couponIds.length; i++) {
				String couponId = couponIds[i];
				if (StringHelper.isNotBlank(couponId)) {
					UsersCouponExample examplec = new UsersCouponExample();
					com.itic.mall.system.users.usercoupon.persistence.model.UsersCouponExample.Criteria criteriac = examplec
							.createCriteria();
					criteriac.andIsEffectiveEqualTo(DBConst.TRUE);
					criteriac.andCouponIdEqualTo(couponId);
					criteriac.andIsUsedEqualTo(DBConst.FALSE);
					criteriac.andUserIdEqualTo(userId);
					List<UsersCoupon> listc = usersCouponService.list(examplec);
					if (listc.size() > 0) {
						UsersCoupon usersCoupon = new UsersCoupon();
						usersCoupon = listc.get(0);
						result = usersCouponService.delete(usersCoupon);
					}
				}
			}

		} catch (Exception e) {
				logException("getcouponAmount", "getcouponAmount", e.toString(), "多个券ID获取券金额总额", e);
			}
			return result;		
		}
		/**
		 * 多个券ID获取券金额总额
		 * @param couponIdstr
		 * @return
		 */
		public double getcouponAmount(String couponIdstr){
			double couponAmount = 0;
			String[] couponIds = null;   
			try{
				couponIds = couponIdstr.split(",");
				for(int i=0;i<couponIds.length;i++){
					String couponId = couponIds[i];
					if (StringHelper.isNotBlank(couponId)) {
						UsersCouponExample examplec = new UsersCouponExample();
						com.itic.mall.system.users.usercoupon.persistence.model.UsersCouponExample.Criteria criteriac = examplec
								.createCriteria();
						criteriac.andIsEffectiveEqualTo(DBConst.TRUE);
						criteriac.andIdEqualTo(couponId);
						criteriac.andIsUsedEqualTo(DBConst.FALSE);
						List<UsersCoupon> listc = usersCouponService.list(examplec);
						if (listc.size() > 0) {
							couponAmount = couponAmount + listc.get(0).getAmount();
						}
					}
				}
			}catch(Exception e){
				logException("getcouponAmount", "getcouponAmount", e.toString(), "多个券ID获取券金额总额", e);
			}
			return couponAmount;
		}
		
		/**
		 * 根据商品ID获取商品信息
		 * @param spuid
		 * @return
		 */
		public GoodsSpu getgoodsDetailSale(String spuid){
			GoodsSpu goodsSpu = new GoodsSpu();
			if(StringHelper.isNotBlank(spuid)){
				GoodsSpuExample example = new GoodsSpuExample();
				com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample.Criteria criteria = example.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andIdEqualTo(spuid);
				List<GoodsSpu> list = goodsSpuService.list(example);
				if(list.size()>0){
					goodsSpu = list.get(0);
				}
			}
			return goodsSpu;
		}

		/**
		 * 根据商品ID获取商品规格参数
		 * @param goodsId
		 * @return
		 */
		public Map<String,Object> getgoodsParamByGoodsId(String goodsId){
			Map<String, Object> paramMap = new HashMap<String, Object>();
			try{
				//商品规格属性
				ParamGoodsExample examplepg = new ParamGoodsExample();
				com.itic.mall.system.goods.paramgoods.persistence.model.ParamGoodsExample.Criteria criteriapg = examplepg.createCriteria();
				criteriapg.andGoodsIdEqualTo(goodsId);
				List<ParamGoods> listpg = paramGoodsService.list(examplepg);
				if(listpg.size()>0){
					String src = listpg.get(0).getParamData();  
					//解析Json为map
					Map maps = (Map)JSON.parse(src);  
			        for (Object map : maps.entrySet()){  
			        	paramMap.put(((Map.Entry)map).getKey().toString(), ((Map.Entry)map).getValue());
			            System.out.println(((Map.Entry)map).getKey()+"     " + ((Map.Entry)map).getValue());  
			        }  
					
				}
			}catch(Exception e){
				
			}
			return paramMap;
		}
		/**
		 * 根据商品ID获取可用优惠券金额
		 * @param goodsId
		 * @return
		 */
		public double getCouponAmountByGoodsId(String goodsId){
			double couponAmount = 0;
			if(StringHelper.isNotBlank(goodsId)){
				SkuCoupon skuCoupon =  this.skuCouponService.getSkuCouponByGoodId(goodsId);
				if(skuCoupon!=null)
					couponAmount = skuCoupon.getMoney();
			}
			return couponAmount;
		}
		/**
		 * 根据商品获取券ID
		 * @param goodsId
		 * @return
		 */
		public String getCouponIdByGoodsId(String goodsId){
			String couponId = null;
			try{
				if(StringHelper.isNotBlank(goodsId)){
					GoodsCouponExample example = new GoodsCouponExample();
					com.itic.mall.system.goods.coupon.persistence.model.GoodsCouponExample.Criteria criteria = example.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
					criteria.andGoodsIdEqualTo(goodsId);
					List<GoodsCoupon> list = goodsCouponService.list(example);
					if(list.size()>0){
						couponId = list.get(0).getCouponId();
					}
				}
			}catch(Exception e){
				logException("getCouponIdByGoodsId", "getCouponIdByGoodsId", e.toString(), "我的订单", e);
			}		
			return couponId;
		}
		
		public double getUsersCouponAmount(String userId,String spuId){
			double couponAmount = 0;
			UsersCouponExample example = new UsersCouponExample();
			com.itic.mall.system.users.usercoupon.persistence.model.UsersCouponExample.Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andSpuIdEqualTo(spuId);
			List<UsersCoupon> list = usersCouponService.list(example);
			if(list.size()>0){
				//根据券ID去查券金额
				couponAmount = 10;
			}
			return couponAmount;
		}
		
		/**
		 * 根据用户ID和商品ID 查看购物车中是否存在
		 * @param userId
		 * @param goodsId
		 * @return
		 */
		public UsersShoppingCartItem getShoppingCartItem(String userId,String goodsId){
			UsersShoppingCartItem Item = null;
			if(StringHelper.isNotBlank(userId) && StringHelper.isNotBlank(goodsId)){
				UsersShoppingCartItemExample example = new UsersShoppingCartItemExample();
				com.itic.mall.system.users.shoppingcartitem.persistence.model.UsersShoppingCartItemExample.Criteria criteria = example.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andGoodsIdEqualTo(goodsId);
				criteria.andUserIdEqualTo(userId);
    			List<UsersShoppingCartItem> list = usersShoppingCartItemService.list(example);
    			if(list.size()>0){
    				Item = list.get(0);
    			}
			}
			return Item;
		}
		public String addShoppingCart(String userId,String goodsId,int count){
			String result = FAIL;
			if(StringHelper.isNotBlank(userId) && StringHelper.isNotBlank(goodsId)){
				UsersShoppingCartItem Item = getShoppingCartItem(userId,goodsId);
				if(Item != null){
					Item.setCount(count);
					result = usersShoppingCartItemService.edit(Item);
				}
			}
			return result;
		}
		/**
		 * 根据商品号获取券信息
		 * @param goodsId
		 * @return
		 */
		public GoodsCoupon getCouponDetailByGoodsId(String goodsId){
			GoodsCoupon goodsCoupon = new GoodsCoupon();
			try{
				if(StringHelper.isNotBlank(goodsId)){
					GoodsCouponExample example = new GoodsCouponExample();
					com.itic.mall.system.goods.coupon.persistence.model.GoodsCouponExample.Criteria criteria = example.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
					criteria.andGoodsIdEqualTo(goodsId);
					List<GoodsCoupon> list = goodsCouponService.list(example);
					if(list.size()>0){
						goodsCoupon = list.get(0);
					}
				}
			}catch(Exception e){
				
			}		
			return goodsCoupon;
		}
		/**
		 * 根据用户ID获取可用积分
		 * @param userId
		 * @return
		 */
		public Map<String, Object> getPointsByUserId(String userId){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			try{
				if(StringHelper.isNotBlank(userId)){
					UsersPointslogExample example = new UsersPointslogExample();
					com.itic.mall.system.users.pointslog.persistence.model.UsersPointslogExample.Criteria criteria = example.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
					criteria.andUserIdEqualTo(userId);
					List<UsersPointslog> list = usersPointslogService.list(example);
					if(list.size()>0){
						resultMap.put("points", list.get(0).getPoints());
						resultMap.put("amount", list.get(0).getPointsAmount());
					}
				}
			}catch(Exception e){
				
			}		
			return resultMap;
		}
    public Wxpay getWxpayConfig(){
    	Wxpay wxpay = null;
    	WxpayExample example = new WxpayExample();
    	com.itic.mall.system.project.wxpay.persistence.model.WxpayExample.Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	String orgCode = PropertyHelper.getString("org.code");
    	criteria.andOrgCodeEqualTo(orgCode);
    	List<Wxpay> list = wxpayService.list(example);
    	if( list.size()>0 ){
    		wxpay = list.get(0);
    	}
    	return wxpay;
    }
    
    public WxCompanyPay getWxCompanyPay(){
    	WxCompanyPay wxCompanyPay = null;
    	WxCompanyPayExample example = new WxCompanyPayExample();
    	com.itic.mall.system.project.wxcompany.persistence.model.WxCompanyPayExample.Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	List<WxCompanyPay> list = wxCompanyPayService.list(example);
    	if(list.size()>0){
    		wxCompanyPay = list.get(0);
    	}
    	return wxCompanyPay;
    }
    public Alipay getAlipayConfig(){
    	Alipay alipay = null;
    	AlipayExample example = new AlipayExample();
    	com.itic.mall.system.project.alipay.persistence.model.AlipayExample.Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	String orgCode = PropertyHelper.getString("org.code");
    	criteria.andOrgCodeEqualTo(orgCode);
    	List<Alipay> list = alipayService.list(example);
    	if( list.size()>0 ){
    		alipay = list.get(0);
    	}
    	return alipay;
    }
    
    public AlipayCompany getAlipayCompanyConfig(){
    	AlipayCompany alipayCompany = null;
    	AlipayCompanyExample example = new AlipayCompanyExample();
    	com.itic.mall.system.project.alipaycompany.persistence.model.AlipayCompanyExample.Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	List<AlipayCompany> list = alipayCompanyService.list(example);
    	if(list.size()>0){
    		alipayCompany = list.get(0);
    	}
    	return alipayCompany;
    }
    
      /**
	    * 获取所有的模块信息
	    * @return
	    */
	   public List<Map<String, Object>> getMarketModelsByType( String type, String isStore ){
		   MarketModelExample example = new MarketModelExample();
		   example.setOrderByClause("REORDER ASC");
		   com.itic.mall.system.market.marketmodel.persistence.model.MarketModelExample.Criteria criteria = example.createCriteria();
		   criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		   criteria.andIsVisibleEqualTo(DBConst.TRUE);
		   
		   if( StringHelper.isNotBlank(type) ){
			   criteria.andTypeEqualTo(type);
		   }
		   if( !"yun".equals(isStore)  ){
			   criteria.andIsStoreEqualTo(isStore);
		   }
		   
		   List<MarketModel> list = marketModelsService.list(example);
		   example = null;
		   List<Map<String, Object>> tranList2MapList = ValueHelper.tranList2MapList(list, new String[] {"isStore","isVisible","createTime","createUser", "isEffective", "updateTime", "orgCode","reorder","note","type","banner","spuIds"});
		   return tranList2MapList;
	   }
	   
	   
	   /**
	    * 获取一级分类
	    * @param type
	    * @return
	    */
	   public List<Map<String, Object>> getTopCategorysByType( String type ){
		    GoodsCategoryExample example = new GoodsCategoryExample();
	   		example.setOrderByClause("REORDER ASC");
	   		com.itic.mall.system.goods.goodscategory.persistence.model.GoodsCategoryExample.Criteria criteria = example.createCriteria();
	   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   		criteria.andLevelEqualTo("1");
	   		if( StringHelper.isNotBlank(type) ){
	   			criteria.andTypeLike("%"+type+"%");
	   		}
	   		List<GoodsCategory> list = goodsCategoryService.list(example);
	   	    List<Map<String, Object>> tranList2MapList = ValueHelper.tranList2MapList(list, new String[] { "note","reorder","categoryCode","createUser", "isEffective", "updateTime", "orgCode","isVisible","createTime","pid","isHot","type","level"});
	   		return tranList2MapList;
      }
	   
	   
	   /**
	    * 获取二级分类的热门分类
	    * @param type
	    * @return
	    */
	   public List<Map<String, Object>> getHotCategorysByType( String type ){
		    GoodsCategoryExample example = new GoodsCategoryExample();
	   		example.setOrderByClause("REORDER ASC");
	   		com.itic.mall.system.goods.goodscategory.persistence.model.GoodsCategoryExample.Criteria criteria = example.createCriteria();
	   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   		criteria.andLevelEqualTo("2");
	   		criteria.andIsHotEqualTo(DBConst.TRUE);
	   		if( StringHelper.isNotBlank(type) ){
	   			criteria.andTypeEqualTo(type); 
	   		}
	   		List<GoodsCategory> list = goodsCategoryService.list(example);
	   	    List<Map<String, Object>> tranList2MapList = ValueHelper.tranList2MapList(list, new String[] { "note","reorder","categoryCode","createUser", "isEffective", "updateTime", "orgCode","isVisible","createTime","pid","isHot","type","level"});
	   		return tranList2MapList;
      }
	   
	   
	   /**
	    * 根据一级类别获取子级分类信息
	    * @param type
	    * @return
	    */
	   public List<Map<String, Object>> getSubCategorysByType( String pid ){
		    GoodsCategoryExample example = new GoodsCategoryExample();
	   		example.setOrderByClause("REORDER ASC");
	   		com.itic.mall.system.goods.goodscategory.persistence.model.GoodsCategoryExample.Criteria criteria = example.createCriteria();
	   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   		criteria.andPidEqualTo(pid);
	   		List<GoodsCategory> list = goodsCategoryService.list(example);
	   	    List<Map<String, Object>> tranList2MapList = ValueHelper.tranList2MapList(list, new String[] { "note","reorder","categoryCode","createUser", "isEffective", "updateTime", "orgCode","isVisible","createTime","pid","isHot","type","level"});
	   		return tranList2MapList;
      }
	   
	   /**
	    * 获取一级分类下的二级分类
	    * @param type
	    * @return
	    */
	   public List<Map<String, Object>> getSubCategorysByPid( String id ){
		    GoodsCategoryExample example = new GoodsCategoryExample();
	   		example.setOrderByClause("REORDER ASC");
	   		com.itic.mall.system.goods.goodscategory.persistence.model.GoodsCategoryExample.Criteria criteria = example.createCriteria();
	   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   		criteria.andLevelEqualTo("2");
	   		criteria.andPidEqualTo(id);
	   		List<GoodsCategory> list = goodsCategoryService.list(example);
	   	    List<Map<String, Object>> tranList2MapList = ValueHelper.tranList2MapList(list, new String[] { "note","reorder","categoryCode","createUser", "isEffective", "updateTime", "orgCode","isVisible","createTime","pid","isHot","type","level"});
	   		return tranList2MapList;
      }
	   
	   /**
	    * 获取一级分类
	    * @param type
	    * @return
	    */
	   public List<Map<String, Object>> getSubCategorysByPcode( String pcode ){
		    GoodsCategoryExample example = new GoodsCategoryExample();
	   		example.setOrderByClause("REORDER ASC");
	   		com.itic.mall.system.goods.goodscategory.persistence.model.GoodsCategoryExample.Criteria criteria = example.createCriteria();
	   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   		//criteria.andLevelEqualTo("2");
	   		criteria.andCodeidLike("%"+pcode+"%");
	   		criteria.andCodeidNotEqualTo(pcode);
	   		List<GoodsCategory> list = goodsCategoryService.list(example);
	   	    List<Map<String, Object>> tranList2MapList = ValueHelper.tranList2MapList(list, new String[] { "note","reorder","categoryCode","createUser", "isEffective", "updateTime", "orgCode","isVisible","createTime","pid","isHot","type","level"});
	   		return tranList2MapList;
      }
	   
	   /**
	    * 根据商品类型和活动类型获取商品信息
	    * @param request
	    * @param spuType 商品类型
	    * @param activityType 活动类型
	    * @return
	    */
	   public Map<String, Object> getGoodsBySpuFromAndType( HttpServletRequest request, String type,
				String keyword, String categoryId, String categoryCode, String orderType, String goodsType ){
		    Map<String, Object> dataMap = new HashMap<String, Object>();
		   
		    GoodsSpuExample example = new GoodsSpuExample();
			if ( StringHelper.isNotBlank(orderType) && !"zonghe".equals(orderType) ) {
				if ("priceDesc".equals(orderType)) {
					example.setOrderByClause("PRICE DESC");
				}
				if ("priceAsc".equals(orderType)) {
					example.setOrderByClause("PRICE ASC");
				}
				if ("conpriceDesc".equals(orderType)) {
					example.setOrderByClause("CON_PRICE DESC");
				}
				if ("conpriceAsc".equals(orderType)) {
					example.setOrderByClause("CON_PRICE ASC");
				}
				if ("commissionDesc".equals(orderType)) {
					example.setOrderByClause("WL_COMMISSION ASC");
				}
				if ("commissionAsc".equals(orderType)) {
					example.setOrderByClause("WL_COMMISSION ASC");
				}
				if("couponMoneyAsc".equals(orderType) ){
					example.setOrderByClause("COUPON_MONEY ASC");
				}
				if("couponMoneyDesc".equals(orderType) ){
					example.setOrderByClause("COUPON_MONEY DESC");
				}
				if("totalSalesAsc".equals(orderType) ){
					example.setOrderByClause("TOTAL_SALES ASC");
				}
				if("totalSalesDesc".equals(orderType) ){
					example.setOrderByClause("TOTAL_SALES DESC");
				}
				if("percentAsc".equals(orderType) ){
					example.setOrderByClause("WL_COMMISSION_SHARE ASC");
				}
				if("percentDesc".equals(orderType) ){
					example.setOrderByClause("WL_COMMISSION_SHARE DESC");
				}
			} else {
				example.setOrderByClause("UPDATE_TIME DESC");
			}

			com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample.Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);// 是否有效
			criteria.andIsShowEqualTo(DBConst.TRUE);// 是否可见

			if (StringHelper.isNotBlank(type)) {
				criteria.andSpuPlatformEqualTo(type);
			}
			if (StringHelper.isNotBlank(keyword)) {
				criteria.andGoodsNameLike("%" + keyword + "%");
			}
			if (StringHelper.isNotBlank(goodsType)) {
				if ("hot".equals(goodsType)) {
					criteria.andIsHotEqualTo("1");
				} else if ("jing".equals(goodsType)) {
					criteria.andIsJingpingEqualTo("1");
				} else if ("special".equals(goodsType)) {
					criteria.andIsSpecialEqualTo("1");
				}else if("fullcut".equals(goodsType)){
					criteria.andIsFullCutEqualTo("1");
				}
			}

			if (StringHelper.isNotBlank(categoryId)) {
				criteria.andCategoryIdEqualTo(categoryId);
			}
			
			if (StringHelper.isNotBlank(categoryCode)) {
				criteria.andCategoryCodeidLike("%"+categoryCode+"%");
			}

			this.handlePageQueryDefault(request, example);// 分页
			int count = goodsSpuService.count(example);// 总条数
			List<GoodsSpu> list = goodsSpuService.list(example);// 数据list

			dataMap.put("total", count);
			dataMap.put("isMore", isMore(request, count));

			dataMap.put("list", ValueHelper.tranList2MapList(list,spuIgnoreProperties));
			return dataMap;
	   }
	   
	   public Map<String,String> parseSkuIdCounts(String skuIdCounts){
			Map<String, String> skuMap = new HashMap<>();
			String skus[] = skuIdCounts.split(",");
			for(String sku : skus) {
				String skuCounts []= sku.split(":");
				int count = skuCounts[1].isEmpty()?1:Integer.parseInt(skuCounts[1]);
				skuMap.put(skuCounts[0],skuCounts[1]);
			}
			return skuMap;
		}
	   
	   /**
	    * 获取所有的活动专题信息
	    * @return
	    */
	   public List<Map<String, Object>> getMarketActivitysByType(String type){
		   MarketActivityExample example = new MarketActivityExample();
		   example.setOrderByClause("REORDER ASC");
		   com.itic.mall.system.market.marketactivity.persistence.model.MarketActivityExample.Criteria criteria = example.createCriteria();
		   criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		   criteria.andIsVisibleEqualTo(DBConst.TRUE);
		   if( StringHelper.isNotBlank(type) ){
			   criteria.andTypeEqualTo(type);
		   }
		   List<MarketActivity> list = marketActivityService.list(example);
		   example = null;
		   List<Map<String, Object>> tranList2MapList = ValueHelper.tranList2MapList(list, new String[] {"isVisible","createTime","createUser", "isEffective", "updateTime", "orgCode","reorder","note","topTitle","subTitle","name","type","activityDesc","banner"});
		   return tranList2MapList;
	   }
	   
	   
	   /**
	     * 根据用户生成一个新的TOKEN
	     * @param user
	     * @return
	     */
	    public UsersToken createToken( UsersMall user, String appId ){
	    	Date date = new Date();
	    	//六个必须字段
	    	UsersToken token = new UsersToken();
	    	token.setId(IdGen.uuid());
	    	token.setIsEffective(DBConst.TRUE);
	    	token.setCreateTime(date);
	    	token.setUpdateTime(date);
	    	token.setOrgCode(ORG_CODE);
	    	token.setCreateUser(CREATE_USER);
	    	//关联字段
	    	token.setUserId(user.getId());//关联用户ID
	    	//三个业务字段
	    	token.setIsOffsite(DBConst.FALSE);
	    	token.setUnionId(user.getUnionid());//微信统一 ID
	    	token.setOpenid(user.getOpenid());//微信公众号ID
	    	token.setAccessToken(getToken());//设置TOKEN
	    	token.setExpiredTime(getExpiredTimeToken(date));//设置有效期
	    	token.setAppId(appId);//设备ID
	    	token.setUserPhone(user.getUserPhone());//用户手机号码
	    	token.setUserNickName(user.getUserNickName());//用户昵称
	    	return token;
	    }
	    
	    /**
		 * 获得海报图片URL
		 * @param goodsSpu
		 * @param user
		 * @return
		 */
	    public String getPoster(GoodsSpu goodsSpu, UsersMall user) {
		    //查找数据库中有没有这个海报，如果有就直接拿来，没有就生成一个
			 //二合一转链接,如果优惠券没有成功转链接，就返回空,如果不是优惠券商品，则正常链接
			String result = "";
			List<ShareHistory> list = shareHistoryService.listBySpuIdAndUserId( goodsSpu.getId(), user.getId() );
			if( list.size()>0 ){
				ShareHistory shareHistory = list.get(0);
				if( StringHelper.isNotBlank(shareHistory.getPosterUrl()) ){
					result = shareHistory.getPosterUrl();
				}else{
					//生成一个新的海报
					String posterUrl = goodsSpuService.getPoster(goodsSpu,shareHistory.getId(),user.getId());
					if( StringHelper.isNotBlank(posterUrl) ){
						shareHistory.setPosterUrl( posterUrl );
					}
					shareHistoryService.edit(shareHistory);
					result = posterUrl;
				}
			}else{
				//添加一个分享记录
				String historyId = IdGen.uuid();
				String posterUrl = goodsSpuService.getPoster(goodsSpu,historyId,user.getId());
				ShareHistory shareHistory = new ShareHistory();
				if( StringHelper.isNotBlank(posterUrl) ){
					shareHistory.setPosterUrl( posterUrl );
				}
				shareHistory.setId(historyId);
				shareHistory.setUserId(user.getId());
				shareHistory.setReorder(0);
				shareHistory.setSpuId(goodsSpu.getId());
				if( goodsSpu.getCouponMoney()>0 ){
					shareHistory.setLinkType("coupon");
				}else{
					shareHistory.setLinkType("common");
				}
				shareHistoryService.add(shareHistory);
				
				result = posterUrl;
			}
			return result;
			
		}
	    
	    /**
	     * 将链接转成二维码链接
	     * @param str
	     * @return
	     */
	    public String getQcodeByString( String str ){
	    	String result = null;
			
			StringBuffer sb = new StringBuffer();
			String url = "http://file.jhjvip.cn:8888/image-server/uploadImage/oss/qcode";
			
			sb.append("url="+str);
			String sendPost = HttpRequestUtils.sendPost(url, sb.toString());
			JSONObject fromObject = JSONObject.fromObject(sendPost);
			String resultRemote = fromObject.getString("errorCode");
			if( "10000".equals(resultRemote)){
				result = fromObject.getString("data");
			}
			return result;
	    }
	    
	    public UsersMall CurUsersMall(HttpServletRequest request) {
	    	Object usersMall = request.getAttribute(RequestUser);
	    	if(usersMall!=null && usersMall instanceof UsersMall)
	    		return (UsersMall) usersMall;
	    	else
	    		return null;
	    }

	    /**
	     * 添加点击量
	     * @param spu
	     */
	    public void addClick( GoodsSpu spu ){
	    	if( null != spu ){
	    	    Integer totalClick = spu.getTotalClick();
	    	    if( null == totalClick ){
	    	    	totalClick = 0;
	    	    }
	    	    spu.setTotalClick(totalClick+1);
	    	    goodsSpuService.edit(spu);
	    	}
	    }
	    
	    /**
	     * 添加分享次数
	     * @param spu
	     */
	    public void addShare( GoodsSpu spu ){
	    	if( null != spu ){
	    	    Integer totalShare = spu.getTotalShare();
	    	    if( null == totalShare ){
	    	    	totalShare = 0;
	    	    }
	    	    spu.setTotalShare(totalShare+1);
	    	    goodsSpuService.edit(spu);
	    	}
	    }
}